Passing context with binding in backbone.js

I want my panels to re-display themselves when clicked.

However, when I click, I get the following:

Uncaught TypeError: Cannot call method 'get' of undefined 

It looks like the β€œthis” that I am registering is actually the model itself:

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

It’s hard for me to understand why the corresponding β€œthis” is not saved by passing my context to model.bind.

Here is my code:

 // 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(); } }); 
+6
source share
2 answers

The main way to do this is to use the _.bindAll(...) function, provided by the underscore:

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

What _.bindAll does is documenting here , but it is essentially built for that very purpose. If you want to set this correctly in all functions of an object, you can call _.bindAll(this) without a list of functions. I tend to have this global binding function in most of my views.

+16
source

I ran into the same problem and ended up using the underscore.js _.bind () method. I requested SO for a response, and that was the answer I received.

Try changing: this.model.bind("change", this.render, this)

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

+13
source

Source: https://habr.com/ru/post/896293/


All Articles