Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone Render View on model update

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

like image 337
Tamil Avatar asked Dec 19 '12 16:12

Tamil


People also ask

How do you're render the view in Backbone JS?

You can override the Backbone. js render method by adding your own code to render the view template from model data and update HTML. This method will contain logic on how to render the template that renders the view.

Is Backbone JS still used?

Backbone. Backbone has been around for a long time, but it's still under steady and regular development. It's a good choice if you want a flexible JavaScript framework with a simple model for representing data and getting it into views.

Is backbone a MVC?

Backbone. js is a model view controller (MVC) Web application framework that provides structure to JavaScript-heavy applications. This is done by supplying models with custom events and key-value binding, views using declarative event handling and collections with a rich application programming interface (API).

What is El property of backbone JS view?

The Backbone. js View el method defines the element that is used as the view reference. this. el is created from the view's tagName, className, id and attributes properties, if specified.


1 Answers

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.

like image 72
jevakallio Avatar answered Sep 19 '22 18:09

jevakallio