2

Question

How can in update Backbone el when re-rendering on model changes?


I Currently have an event listener, listening to model changes like this.

this.listenTo(this.model, 'change', this.render);

This will then re-render the view correctly however the className & attributes are not updated to reflect the model changes, they look like this.

className: function()
{
    var childClassName  = ( null === this.model.get('parent_id') ? '' : ' list-item-child' ),
        parentClassName = ( false == this.model.get('parent') ? '' : ' list-item-parent');

    return 'list-item' + childClassName + parentClassName;
},

attributes: function()
{
    return {
        'data-id': this.model.get('id'),
        'data-parent': this.model.get('parent_id')
    }
},
Kyle Needham
  • 3,379
  • 2
  • 24
  • 38
  • maybe this answer can help you: http://stackoverflow.com/questions/18330877/set-dynamically-classname-on-backbone-view-render – Frogmouth Feb 18 '14 at 15:53

2 Answers2

2

You have to update yourself, for instance:

onRender: function(){

  this.$el.removeClass().addClass(this.className());

}
moonwave99
  • 21,957
  • 3
  • 43
  • 64
1

The className is set at the view creation, when you rerender the view it wont be updated.

If you have no other solution, maybe this solution can help you :

this.listenTo(this.model, 'change', function() {
    this._ensureElement();
    this.render();
    this.delegateEvents();
});
Rida BENHAMMANE
  • 4,111
  • 1
  • 14
  • 25