View automatic updates in backbone.js

I use backbone.js and have a model without a collection. In the view, I call fetch on the callback model to render the view.

this.user.fetch({success: function(d) { self.randomUserView.render() }})

How can I automatically update the view when the model changes? for example, I don’t want to specify the above callback every time I call the select. I tried to bind the view to many model events during initialization, but this did not work.

+5
source share
3 answers

In the view, add an event handler to the view model:

initialize: function() {
  this.model.on('change',this.render,this);
}
+12
source

, ( ). Backbone. fetch(), "". , , initialize:

initialize: function() {
  ... your code...
  this.model.bind('add', this.render);
}

init - .

+1

In fact, if you want to update the view while retrieving the collection, you need to bind RESET!

this.model.bind('reset', this.render, this);

The update only starts when editing the current collection.

ps bindAll is dangerous and lazy. (and is likely to cause problems on the line)

0
source

All Articles