1

Is there a way in which I can make functions that are specific to the template and accessible by the template's event handlers? I don't want to pollute the global namespace.

I came upon this problem when I first noticed that I was repeating a lot of code between my event handlers in a manner similar to this:

Template.options.events({
    "click .btn-1": function(e) {
        // do something
        var div;
        div = $(e.target);
        if (div.hasClass("active")) {
          return div.removeClass("active");
        } else {
          return div.addClass("active");
        }
      },
    "click .btn-2": function(e) {
        // do something else
        var div;
        div = $(e.target);
        if (div.hasClass("active")) {
          return div.removeClass("active");
        } else {
          return div.addClass("active");
        }
    }
});

Note that I'm not trying to find a way to combine selectors, I already know how to do that. Notice that each button does something different, but have a few lines of repeated code. I want to keep this as DRY as possible without polluting the global namespace.

4

1 回答 1

2

Meteor 项目中的每个文件都有自己的本地范围。如果您在一个文件中使用function blah() { ... } or定义一个函数var blah = function () { ... },则在该文件之外将无法访问该函数。只有blah = function () { ... }(没有var)定义了一个真正的全局。

如果这还不够,您可以在立即调用的函数表达式 (IIFE) 中定义局部函数:

(function () {
    function toggleActive(div) {
        if (div.hasClass("active")) {
            div.removeClass("active");
        } else {
            div.addClass("active");
        }
    }

    Template.options.events({
        "click .btn-1": function (e) {
            // do something
            toggleActive($(e.target));
        },
        "click .btn-2": function (e) {
            // do something else
            toggleActive($(e.target));
        }
    });
})();

// toggleActive is inaccessible here
于 2015-03-06T12:23:57.787 回答