2011-08-31 16 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 

मैं मुझे यह समझने में परेशानी हो रही है कि उपयुक्त "यह" मॉडल में मेरे संदर्भ को पारित करके संरक्षित क्यों नहीं है।

// 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())); 
} 

क्या _.bindAll करता here प्रलेखित है: this.model.bind("change", _.bind(this.render, this))

+1

दोषहीन। आप राज। – nottombrown