How to update the view without re-rendering in marionette.js

4.1k Views Asked by At

How to update the view with the model.fetch(), i.e when i fetch the model, the view shouldn't be destroyed or re-rendered. It should just update the new model into view with reseting the previous model.

this.model.fetch({success: this.render.bind(this)});

This code is re-rendering my view..How can i just update the view with new model

Thanks.

2

There are 2 best solutions below

1
On

Whenever you establish a double binding with your model attributes to the templates, your views need to be rendered again to show the changes. So, you can't avoid rendering to show the updated status of your model.

But what I would suggest you to do is to divide your view into subviews. Since, you are using marionette, you can create a main layout which contains all the regions and for each small region, you can define a view .

For example , suppose I have a basic form with my name, current time and age . All of these variables are stored in a model . So, you have a scenario where your name and age hardly changes but the current time is changing every millisecond causing your whole view to re-render which is bad in terms of performance as well as to the eyes.

So, in order to solve the above scenario, if you could create a separate view for the current-time element, you can render is separately and other elements don't need to be rendered again and again. You can always define a separate view for a single button element if you think that its functionality can be abstracted.

0
On

There are multiple ways of updating the view based on your need.

  1. If the view is fairly simple, and all that is needed is to automatically update the view on model's fetch, rendering the view again is the simplest(Backbone's sync event on the model can be used, and model events can be handled declaratively using Marionette View's modelEvents hash -http://marionettejs.com/docs/marionette.view.html#viewmodelevents-and-viewcollectionevents)

    modelEvents: {'sync': 'render'}
    
  2. If you have few model attributes that change in a complex view, you could directly update the dom elements via jquery by listening to change events on the model attributes:

    modelEvents: {'change:name':'nameChanged'}, 
    nameChanged: function(model, value){ this.$('#name').val(value);}
    
  3. If Two way data binding between view and model is needed, frameworks like Backbone.stickit can be used to this purpose - https://github.com/NYTimes/backbone.stickit#usage