Frank
Frank

Reputation: 2173

Render parts of a template

I have a Backbone view and I'm using Handlebars to load templates in my view.

I have a list #list in the template that have to be updated in the view and after that it needs to be re-rendered. I want to re-render only the part that has changed so only #list without reload all my DOM (and so all the Handlebars helpers that I have).

I tried this:

template: Handlebars.compile(templateHtml),

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

renderList: function() {
  var html = this.template(this.model.toJSON());
  var selector = "#list";

  this.$el.find(selector).replaceWith($(selector, html));
}

but this is very slow because I think it re-renders all DOM before changing the #list content as I need.

Is there any better way to do that?

Is it a good idea to put the content of #list in another template and load it as a subView? In this case how can I trigger an update of the list from my first view?

Thanks

Upvotes: 0

Views: 173

Answers (1)

Yura
Yura

Reputation: 2721

It is better to update just the part of your rendered view by creating a dedicated render method, something I explained here.

In your situation it looks like you have to build whole html view from template, just to update the part of it. Which is neat, if you want to keep the template as one template.

If there really a lot of going on in the template beyond the list, you could have two templates in your view, one will be the general one, and the other one just for the list, which you will mount into the first one on global render, with the benefit of being able to update just the list.

Further, you might not even need a second template if the #list is simply a container for a list. I can imagine that might be an <ul> tag which you will mount at the right place during the global render, and then update it with other custom render methods.

Also, I wrote an example here, which might be potentially helpful in your case: Backbone.js fetch() JSON to model get() returnes undefined - in the example there's a template, that has a container for a list, and the list is managed separately by it's own collection.

Just some thoughts.

Upvotes: 1

Related Questions