I use backbone.js and have a model without a collection. In the view I call fetch on the model with a callback to render the view.
this.user.fetch({success: function(d) { self.randomUserView.render() }})
how can I make the view update automatically when the model change? e.g. I don't want to specify the above callback every time I call fetch. I tried to bind the view to many model events on initialize but this did not work.
Backbone. js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.
BackboneJS allows developing of applications and the frontend in a much easier way by using JavaScript functions. BackboneJS provides various building blocks such as models, views, events, routers and collections for assembling the client side web applications.
Unlike most of the MVC frameworks, Backbone. js consists of six main components: Models, Views, Collections, Events, Routers and Sync.
It is also known as the heart of the JavaScript application. Model contains dynamic data and its logic. It performs various types of action on the data like validation, conversion, computed properties, access control etc. 1.
On the view, add an event handler to the view's model:
initialize: function() {
this.model.on('change',this.render,this);
}
Backbone is event-driven, not callback driven framework (although technically they are callbacks). And your approach does not seem to be native to Backbone. When you do fetch(), user model will automatically trigger "add" event. All you need to do is in the corresponding view add this in initialize:
initialize: function() {
... your code...
this.model.bind('add', this.render);
}
This way you subscribe to this even only once in the view init and don't have to ever pass explicit callbacks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With