2011-08-31 10 views
6

クリックしたときにパネルが再レンダリングされるようにしたい。私はクリックを実行するときbackbone.jsでのバインドによるコンテキストの受け渡し

はしかし、私は次を得る:

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

I:

Uncaught TypeError: Cannot call method 'get' of undefined 

"これは" 私がログインしてるということは、実際にモデル自身であることが表示されます私のコンテキストを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(...)機能を使用することです本質的にこの目的のために作られています。 thisをオブジェクトのすべての関数に正しく設定したい場合は、関数リストなしで_.bindAll(this)を呼び出すことができます。私はこの大域バインド機能を私の意見の大部分に持つ傾向があります。

13

は、私は同じ問題に遭遇し、代わりにunderscore.jsの_.bind()メソッドを使用して終了:

は、ここに私のコードです。私は応答のためにSOを尋ねた、そしてそれは私が得た返答だった。

は変更してみてください:this.model.bind("change", this.render, this)

へ:hereを文書化されていない何_.bindAll

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

:これを行うのthis.model.bind("change", _.bind(this.render, this))

+1

完璧です。あなたは支配する。 – nottombrown

関連する問題