简体   繁体   English

在Backbone.js中绑定它

[英]Binding this in Backbone.js

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. 这在大多数情况下都是正常的,除了在addFriendLi里面,this.friends返回undefined。 Meaning this is not bound to the current model instance. 这意味着它不绑定到当前模型实例。 But I followed the instructions and called _.bindAll(this,"addFriendLi") . 但我按照说明调用了_.bindAll(this,"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移动到集合构造函数之上来修复此问题

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

From what i can see the following should do the trick 从我可以看到以下应该做的伎俩

_.bindAll("addFriendLi") _.bindAll( “addFriendLi”)

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

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