开发者

Binding this in Backbone.js

开发者 https://www.devze.com 2023-02-28 20:54 出处:网络
I have a simple demo app like this Friend = Backbone.Model.extend name:null Friends = Backbone.Collection.extend

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

0

精彩评论

暂无评论...
验证码 换一张
取 消