Search code examples
javascriptbackbone.jsbackbone-eventsmarionettebackbone-relational

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.


Solution

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