gpt4 book ai didi

javascript - Backbone 和 bindAll : "func is undefined"

转载 作者:搜寻专家 更新时间:2023-11-01 04:45:21 24 4
gpt4 key购买 nike

我在使用 bindAll 时遇到问题。我收到的错误是 func is undefined。对我做错了什么有什么想法吗?

我都试过了

  • bindAll(因上述错误而失败)和
  • 个人 bind(不工作)
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

在这里搜索“fat arrow”:http://jashkenas.github.com/coffee-script/

但是,关于 _.bindAll,您不需要以数组形式提供方法名称。您可以执行 _.bindAll(this)_.bindAll(this, 'render', 'foo') (方法名称是 var args,而不是显式列表).看看是否有帮助。

关于javascript - Backbone 和 bindAll : "func is undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6613086/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com