在 Backbone.js 中绑定它
我有一个像这样的简单演示应用程序,
Friend = Backbone.Model.extend
name:null
Friends = Backbone.Collection.extend
initialize: (models,options)->
this.bind("add",options.view.addFriendLi)
AppView = Backbone.View.extend
el: $("body")
initialize: ->
this.friends = new Friends(null,view:this)
_.bindAll(@,"addFriendLi")
events:
"click #add-friend": "showPrompt"
showPrompt: ->
friend_name = prompt("who is your friend?")
friend_model = new Friend(name:friend_name)
this.friends.add(friend_model)
addFriendLi : (model) ->
console.debug this.friends #returns undefined
if model.get("name")?
item = $("<li>"+model.get("name")+"</li>")
item.appendTo("#friends-list")
appview = new AppView
除了在 addFriendLi
内部 this.friends 返回未定义之外,它在大多数情况下都可以正常工作。这意味着这不绑定到当前模型实例。但我按照说明调用了_.bindAll(this,"addFriendLi")
。我不明白为什么这不起作用。
I have a simple demo app like this
Friend = Backbone.Model.extend
name:null
Friends = Backbone.Collection.extend
initialize: (models,options)->
this.bind("add",options.view.addFriendLi)
AppView = Backbone.View.extend
el: $("body")
initialize: ->
this.friends = new Friends(null,view:this)
_.bindAll(@,"addFriendLi")
events:
"click #add-friend": "showPrompt"
showPrompt: ->
friend_name = prompt("who is your friend?")
friend_model = new Friend(name:friend_name)
this.friends.add(friend_model)
addFriendLi : (model) ->
console.debug this.friends #returns undefined
if model.get("name")?
item = $("<li>"+model.get("name")+"</li>")
item.appendTo("#friends-list")
appview = new AppView
This works normal for the most part except that inside addFriendLi
this.friends returns undefined. Meaning this is not bound to the current model instance. But I followed the instructions and called _.bindAll(this,"addFriendLi")
. I don't understand why that doesn't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我通过将bindAll移动到集合构造函数上方来解决这个问题,如下所示
I fixed this issue by moving the bindAll above the collection constructor like this
据我所知,以下应该可以解决问题
_.bindAll("addFriendLi")
From what i can see the following should do the trick
_.bindAll("addFriendLi")