我在使用 bindAll 时遇到了问题。我得到的错误是 func is undefined
。对我做错了什么有任何想法吗?
我都尝试过
bindAll
(因上述错误而失败)和 bind
s(不工作)window.test = Backbone.View.extend({
collection: null
initialize: ->
console.log('initialize()')
console.log(this)
# _.bindAll(this, ["render", "foo"])
_.bind(this.render, this) # these don't throw errors, but binding won't work
_.bind(this.foo, this)
@collection = new Backbone.Collection()
@collection.bind "add", @render
@collection.bind "add", @foo
@render()
foo: ->
# won't be bound to the view when called from the collection
console.log("foo()")
console.log(this)
console.log(this.collection) # undefined (since this is the collection, not the view)
render: ->
console.log("render()")
console.log(this)
return this
})
testInstance = new window.test();
# using _.bind instead of bindAll we get past this point, however this won't be the view
testInstance.collection.add({})
最佳答案
您正在使用 CoffeeScript,您不需要下划线的绑定(bind)。 CoffeeScript 内置了它。只需使用“粗箭头”
foo: =>
#Your foo implementation goes here
render: =>
# your render implementation goes here
在此处搜索“胖箭头”:http://jashkenas.github.com/coffee-script/
但是,对于
_.bindAll
,您不需要将方法名称作为数组提供。您可以执行 _.bindAll(this)
或 _.bindAll(this, 'render', 'foo')
(方法名称是 var args,而不是显式列表)。看看是否有帮助。