简体   繁体   中英

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. 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.

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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