Javascript 将其绑定到Backbone.js中
我有这样一个简单的演示应用程序Javascript 将其绑定到Backbone.js中,javascript,backbone.js,Javascript,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
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
_.bindAll(@,"addFriendLi")
this.friends = new Friends(null,view:this)
Friend=Backbone.Model.extend
名称:空
Friends=Backbone.Collection.extend
初始化:(模型、选项)->
this.bind(“添加”,options.view.addFriendLi)
AppView=Backbone.View.extend
el:$(“正文”)
初始化:->
this.friends=新朋友(null,视图:this)
_.bindAll(@“addFriendLi”)
活动:
“单击#添加朋友”:“显示提示”
showPrompt:->
friend\u name=prompt(“谁是你的朋友?”)
friend\u model=新朋友(姓名:friend\u name)
this.friends.add(friends\u模型)
addFriendLi:(型号)->
console.debug this.friends#返回未定义的
如果model.get(“name”)?
item=$(“”+model.get(“name”)+“ ”)
项目。附加到(“朋友列表”)
appview=新建appview
除了在
addFriendLi
This.friends中返回未定义之外,这在大多数情况下都正常工作。这意味着它不绑定到当前模型实例。但是我按照说明打电话给.bindAll(这是“addFriendLi”)
。我不明白为什么这样不起作用。我通过将bindAll移到集合构造函数上方,解决了这个问题,如下所示
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
_.bindAll(@,"addFriendLi")
this.friends = new Friends(null,view:this)
从我所看到的情况来看,下面应该可以做到这一点 _.bindAll(“addFriendLi”)