1

I have a User model that has a BankAccount model and I have view who's model attribute is set to the User model and in that view's template I reference an attribute of the bank account:

<%= bankAccount.get('description') || 'No linked account' %>

If I updated the bankAccount the view doesn't pick up on the change:

user.get('bankAccount').set('description', 'foobar')

I tried adding the following in the initialize on the User model but it didn't work either.

initialize: function() {
  var self = this;

  this.on('change:bankAccount', function() {
    self.get('bankAccount').bind('change', function() {
      self.trigger('change');
    });
  });
}

Any suggestions? Also, both these models use backbone relational, if that helps.

Matt Fletcher
  • 8,182
  • 8
  • 41
  • 60
Adam Langsner
  • 1,276
  • 1
  • 15
  • 23

2 Answers2

3

Have your view subscribe to the description change event on the BankAccount model and re-render itself

UserView = Backbone.View.extend({
  initialize: function() {
    this.model.get('bankAccount').on('change:description', this.render, this);
  }
});
Paul
  • 18,349
  • 7
  • 49
  • 56
1

From the Backbone-relational Events you will see that you can bind to update:<key> and further below there is an example (which I copy/pasted below) on how to listen to changes/updates on HasMany and HasOne relations

// Use the 'update' event to listen for changes on a HasOne relation 
// (like 'Person.livesIn').
paul.bind( 'update:livesIn', function( model, attr ) {
    console.debug( 'update to %o', attr );
});
Claudiu Hojda
  • 1,021
  • 9
  • 14