2017-08-30 81 views
1

我想调用下划线模板内的自定义函数,但是我得到一个错误: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。

回答

3

_.extend不能这样工作,它需要2个或更多的对象,并且键将被合并。 它看起来像你可能从this other question这个片段,但它不正确和/或过时。

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)。为此,您需要在将函数传递给模板时使用.bind(this)

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