繁体   English   中英

在Backbone.js中绑定它

[英]Binding this in 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返回undefined。 这意味着它不绑定到当前模型实例。 但我按照说明调用了_.bindAll(this,"addFriendLi") 我不明白为什么那不起作用。

我通过将bindAll移动到集合构造函数之上来修复此问题

    _.bindAll(@,"addFriendLi")
    this.friends = new Friends(null,view:this)

从我可以看到以下应该做的伎俩

_.bindAll( “addFriendLi”)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM