Callback binding in Backbone.js

According to Backbone.js documentation:

Whenever a user interface action causes a change in a model attribute, the model fires a β€œchange” event; all Views displaying model data are reported on the event, forcing them to re-display.

So, I believe that the render () method should be attached to the "change" event by default. However, the following code does not work:

TestModel = Backbone.Model.extend({}); TestView = Backbone.View.extend({ render: function() { alert('render called'); } }); var mod = new TestModel; var view = new TestView({model:mod}); mod.change(); 

It only works if I add an explicit bind call:

 initialize: function() { this.model.bind('change', this.render, this); } 

Does this mean that my understanding of the render () callback is wrong by default, and we should always bind the render () callback manually?

+6
source share
2 answers

If nothing has changed in the last few months, yes, it is. This is good because it gives flexibility regarding when views are rendered / redrawn (for example, some applications may want to display a view only after the model has been stored on the server, not necessarily when it changes to the browser). If you want your views to always be displayed again when the model attribute changes, you can expand the default baseline view with your own base view, which links its visualization method to the model change event, and then extends all your specific views from this. Example:

 MyView = Backbone.View.extend({ initialize: function() { Backbone.View.prototype.initialize.apply(this, arguments); this.model.bind('change', this.render); } }); MyConcreteView = MyView.extend({...}); var model = new Backbone.Model({...}); var view = new MyConcreteView({model: model}); model.set({prop: 'value'}); 
+6
source

You can override the Backbone.View constructor to set the default rendering callback after creating a new view using the code below:

 Backbone.View = (function(View) { // Define the new constructor Backbone.View = function(options) { // Call the original constructor View.apply(this, arguments); // Add the render callback if (this.model != null) { this.model.bind("change", this.render, this); } else { // Add some warning or throw exception about // the render callback not being triggered } }; // Clone static properties _.extend(Backbone.View, View); // Clone prototype Backbone.View.prototype = (function(Prototype) { Prototype.prototype = View.prototype; return new Prototype; })(function() {}); // Update constructor in prototype Backbone.View.prototype.constructor = Backbone.View; return Backbone.View; })(Backbone.View); 

Now you can create a new view as follows:

 view = new Backbone.View({model: new Backbone.Model}) 
+1
source

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


All Articles