0

After I change an input text field that corresponds to a single attribute in an ItemView, I update all models in my CompositeView.

The update works fine in the models, but only the ItemView corresponding to the last edited input text field displays new attributes in the DOM, as it's the only element in the CompositeView that's getting its onRender method called:

   onRender: function() {
        this.$el.html(this.template(this.model.toJSON()));
        return this;
    }

I want to call the onRender() function again in all the ItemViews inside the CompositeView. How can I do this?

andandandand
  • 21,946
  • 60
  • 170
  • 271

2 Answers2

1

Not the most elegant solution, but here goes

var childViews = compositeView.children._views;
_.each(childViews, function(childView){
    childView.render();
});
Scott
  • 469
  • 5
  • 11
  • Thanks, I ended up using what I mentioned in my answer. I'll try this too. – andandandand Sep 13 '13 at 17:19
  • Thanks! Maybe i didnt understand your question properly but the problem with the method in your answer is that the only itemview that will update is the one whose model has changed, and not all of the itemviews inside the compositeview – Scott Sep 13 '13 at 22:11
1

After reading what appears in this question, and the checking out the documentation. I figured that I would try simply using a change event listener in the ItemView.

myItemView = Backbone.Marionette.ItemView.extend({

    initialize: function() {
        /*bind change event, will get onRender fired when the probability gets updated
        this.model.bind('change', this.onRender);
        error: 'cannot call' Cannot call method 'toJSON' of undefined
        TODO: figure out WHY this is an error but this.render is OK*/

        this.model.bind('change', this.render);
    }

Mysteriously, onRender() fails, but render() does the job. Now I want to figure out why.

Community
  • 1
  • 1
andandandand
  • 21,946
  • 60
  • 170
  • 271
  • 2
    `onRender` is called after `render`. Render is a backbone method that marionette has implemented for you. In order for marionette to still give you some flexibility, theyve provided `onBeforeRender` and `onRender` so that you can customize their default behaviour. These two methods do nothing unless you provide them with functionality, only `render` actually updates the view by default – Scott Sep 13 '13 at 22:08
  • 2
    also, just so ya know, you can also listen to ALL change events in a collection so if one model changes you can update all of your itemviews. `something.listenTo(someCollection, 'change', function(){console.log('an attribute on a model just changed');});` – Scott Sep 13 '13 at 22:22
  • @Scott: Thanks! That clarifies a lot. – andandandand Sep 13 '13 at 22:45