Adam Langsner
Adam Langsner

Reputation: 1286

Bind sub-model to view in backbone / marionette

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.

Upvotes: 1

Views: 877

Answers (2)

Claudiu Hojda
Claudiu Hojda

Reputation: 1051

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 );
});

Upvotes: 1

Paul
Paul

Reputation: 18597

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);
  }
});

Upvotes: 3

Related Questions