13
votes

I'm writing a sample app using backbone.js.

On update of my model I re-render my view in this fashion

$('.target').html("");
$('.target').append(this.$el.html(this.template(model)))

Once the view is re-rendered after model update [on change event], events attached to the el's children gets lost [doesn't seem to be like jQuery live]. Is this a known issue or am I missing something? Should I try to replace html instead of append? fiddle

1
You might want to fix your fiddle so that it runs. eg. using jQuery and including Underscore and Backbone as well - Mike Fielden
you don't need two statements. Just use one: $('.target').html(this.$el.html(this.template(model))), which is equivalent to clearing the HTML and appending a new one - Matanya
@Mike Fielden Then I might need to put my entire app :D I thought the view would suffice to understand my issue - Tamil
@Matanya you are right I hope it worked. Let me do a final testing and comeback. I was initially doing $this.el.html() which missed the wrapper div. But your soln fixed it - Tamil

1 Answers

11
votes

Once the view is in DOM, you don't need to keep removing and appending it. I think the simplest way to manage this is to remove the DOM insertion from the view altogether, and let the caller of view.render to take care of it.

View:

render: function() {
  this.$el.html(this.template(model));
  return this;
}

Caller (on first render):

var view = new SomeView();
$('.target').append(view.render().el);

On subsequent renders:

view.render();

After the view has been rendered into DOM it can keep happily re-rendering itself without having to know anything about parent views. The event bindings should also stay intact between renders.