2011-08-31 5 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() 메소드를 사용하여 결국 :

여기 내 코드입니다. 나는 응답을 위해 그렇게 질문했다. 그리고 내가 가지고있는 대답이었다.

한번에 변경 : this.model.bind("change", this.render, this)

에 :

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

here에 설명되어 있습니다 무엇 _.bindAll : this.model.bind("change", _.bind(this.render, this))

+1

Flawless. 너 규칙. – nottombrown