在 Backbone 视图中定义的下划线模板中调用函数

Calling a function inside underscore template defined in Backbone view

我试图在下划线模板中调用自定义函数,但出现错误:未定义 testFunction。

在我的 backbone 视图中:

initialize: function() {
    this.testFunction = function (x) {
        alert("Hello " + x);
    }
}

render: function() {
    var data = _.extend({"output":output}, this.testFunction);
    $(this.el).html(this.template(data));
    return this;
}

在我的模板中调用测试函数:

<%= testFunction(10) %>

但是我得到一个错误 testFunction is not defined。

_.extend doesn't work like that, it needs 2 or more objects, and the keys will be merged. It looks like you probably took that snippet from this other question,但不正确and/or已过时

extend _.extend(destination, *sources)

Shallowly copy all of the properties in the source objects over to the destination object, and return the destination object. Any nested objects or arrays will be copied by reference, not duplicated. It's in-order, so the last source will override properties of the same name in previous arguments.

_.extend({name: 'moe'}, {age: 50});
=> {name: 'moe', age: 50}

这可行:

_.extend({ output: output }, { testFunction: this.testFunction });

但在这种简单情况下,更好的方法是完全避免 _.extend

this.$el.html(this.template({
    output: output,
    testFunction: this.testFunction
}));

在现实生活中,您可能希望在将函数传递给模板时使用视图 context (this) within the function. To do this, you would need to use .bind(this)

this.$el.html(this.template({
    output: output,
    testFunction: this.testFunction.bind(this)
}));