繁体   English   中英

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

[英]Calling a function inside underscore template defined in Backbone view

我试图在下划线模板中调用自定义函数,但是我收到一个错误:testFunction未定义。

在我的骨干中查看:

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没有定义。

_.extend不能像那样工作,它需要2个或更多对象,并且键将被合并。 看起来您可能从其他问题中获取了该片段,但它不正确和/或过时。

extend _.extend(destination, *sources)

对象中的所有属性复制到目标对象,然后返回目标对象。 任何嵌套对象或数组都将通过引用复制,而不是重复。 它是有序的,因此最后一个源将覆盖先前参数中相同名称的属性。

 _.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
}));

在现实生活中,您可能希望在函数中使用视图上下文( this 为此,在将函数传递给模板时,需要在函数上使用.bind(this)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM