0

I'm using Backbone for a webapp in which I fetch a model from an API call and populate a view with that. Within that view, there are a couple things, among which is a textarea and some sort of chat area (which is populated with other views). So far so good.

I now want to call the API again, and if the initial model changed I want to update parts of that view. My problem is now, that I am afraid that if I reload the view, the things that people might have written in the textarea are gone. I guess I can make a call and update parts of the view using jQuery, but I think that's not really the idea behind Backbone.

So my question is now; how can I use Backbone to update parts of the initial view without reloading the whole view? All tips are welcome?

kramer65
  • 50,427
  • 120
  • 308
  • 488

2 Answers2

1

Typically a view is bound to a model and it represents a part of the DOM. When you say that the view should update when the model changes, my first thought is that this would be a separate view from the inputbox.
For example, there could be one parent view that is represented as a wrapper element, and multiple subviews that represent different models.
You can still manage events from your parent view, because events will bubble up.
It is important to take into account proper view cleanup when you're working with subviews though. Marionette.js is a library that manages this well.

Alternatively, you can temporarily cache the user input and populate the view back after it's rendered.

html_programmer
  • 18,126
  • 18
  • 85
  • 158
0

Your view needs to listen to model changes. If you render your view you pass your model to the template. And in your initialize function of the view you tell yout view the listen to model changes. See here.

var view = Backbone.View.extend({  
         initialize: function(){
           this.model.on('change', this.render, this);
         },
         render: function() {
            // ...
         }
     });
Community
  • 1
  • 1
Marc Radziwill
  • 175
  • 2
  • 12