2011-08-31 19 views
6

我希望面板在點擊時重新呈現自己。在backbone.js中通過綁定傳遞上下文

然而,當我進行點擊,我得到如下:

Uncaught TypeError: Cannot call method 'get' of undefined 

看來,「這」是我記錄實際上是在模型本身:

_callbacks: Object 
_changed: true 
_escapedAttributes: Object 
_previousAttributes: Object 
attributes: Object 
cid: "c0" 
collection: r.d 
id: "f5589ba4-a0aa-dd86-9697-30e532e0f975" 
__proto__: n 

我無法通過將我的上下文傳遞給model.bind來解決爲什麼不保留適當的「this」。

這裏是我的代碼:

// Models 
window.Panel = Backbone.Model.extend({ 

    defaults: function(){ 
     return { 
      flipped: false, 
     }; 
    }, 

    toggle: function(){ 
     this.save({flipped: !this.get("flipped")}); 
    }, 

}); 


// Collections 

window.PanelList = Backbone.Collection.extend({ 

    model:Panel, 

    localStorage: new Store("panels"),  

    flipped: function(){ 
     return this.filter(function(panel){ return panel.get("flipped"); }) 
    } 
}); 


// Global collection of Panels 
window.Panels = new PanelList; 

// Panel View 

window.PanelView = Backbone.View.extend({ 

    tagName: 'div', 

    template: _.template($("#panel-template").html()), 

    events: { 
     "click" : "toggle" 
    }, 

    initialize: function(){ 
     this.model.bind("change", this.render, this) 
     $(this.el).html(this.template(this.model.toJSON())); 
    },  

    render: function(){  
     console.log(this); 
     var flipped = this.model.get("flipped") 
     if (flipped){ 
      $(this.el).addClass("flip"); 
     } else{ 
      $(this.el).removeClass("flip"); 
     }   
     return this 
    }, 

    toggle: function(){ 
     this.model.toggle(); 
    } 
}); 

回答

16

這樣做的骨幹-Y的方法是使用由下劃線提供的_.bindAll(...)功能:

initialize: function(){ 
    _.bindAll(this, "render"); 
    this.model.bind("change", this.render) 
    $(this.el).html(this.template(this.model.toJSON())); 
} 

什麼_.bindAll不會被記錄here ,但它基本上是爲此目的而建造的。如果你想this正確設置全部功能的對象,你可以撥打電話_.bindAll(this)沒有功能列表。我傾向於在我的大部分觀點中都具有這種全局綁定功能。

13

我遇到同樣的問題,並最終使用underscore.js的_.bind()方法來代替。我詢問是否有迴應,這是我得到的答覆。

嘗試改變:this.model.bind("change", this.render, this)

爲:this.model.bind("change", _.bind(this.render, this))

+1

無瑕。你統治。 – nottombrown

相關問題