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开发者_JAVA百科,"addFriendLi")
. I don't understand why that doesn't work.
I fixed this issue by moving the bindAll above the collection constructor like this
_.bindAll(@,"addFriendLi")
this.friends = new Friends(null,view:this)
From what i can see the following should do the trick
_.bindAll("addFriendLi")
精彩评论