I just did something using a trunk that displays an edit text box where you can edit the project name. Since this name is also displayed on the main page, I want to update it at the same time. But I do not want to identify the DOM element and update it directly using my editing. Instead, I create a base model:
this.newModel = new app.Project({model: this.model});
Then I listen to the new model for any changes, in this case for the project_name attribute:
this.listenTo(this.newModel, 'change:project_name', this.updateName);
Then I create a new view using 'newModel'
modal = new app.ProjectModal({ model: this.newModel, });
This is then displayed, and if the name changes in the modal view, the "this.updateName" function is run in the "parent" view, which eliminates the need to identify where the actual DOM element is.
The entire "parent" function looks like this:
app.ProjectCardView = Backbone.View.extend({ tagName: 'article', className: 'project', template: _.template( $("#tpl-project-card-summary").html() ), events: { 'click .settings-btn': 'showProjectModal' }, initialize: function() { //a slightly different model is used to populate project than this card... this.newModel = new app.Project({model: this.model}); return this; }, render: function() { this.$el.html( this.template(this.model.toJSON()) ); return this; }, showProjectModal: function (e) { this.listenTo(this.newModel, 'change:project_name', this.updateName); this.modal = new app.ProjectModal({ model: this.newModel }); return this; }, updateName: function() { if (this.modal) { this.$el.find('.item_name').text(this.model.get("project_name")); } return this; } });
Obviously, I need to update the DOM somewhere, but now it is separate from editing and easier to manage.