BMH
BMH

Reputation: 4330

How to clone views in Backbone?

I have a view and I need to re-render it in the same page.

If I call .render() again the first rendered is gone.

Cloning view object with jQuery.extend() has same result.

var cloneView = $.extend(true, {}, view);
$('#container').append(cloneView.render().el);

I cannot call new View() because there are various view classes.

How can I make a proper clone of a view?

Upvotes: 0

Views: 1564

Answers (2)

anh_ng8
anh_ng8

Reputation: 1170

It is dangerous to go blindly clone any view. You need to check for subtle things like hard-coded IDs in the template and in the view, styles of the template when it's re-used in different locations,..etc.

I would suggest either:

  1. Create a new instance of the view. (if you're sure it's safe to render the another instance simultaneously with the previous instance of the view on the same page).

var my_view = new MyView({ el: $("#id") });

  1. Create a new view extending that view. (this is a better bet)

CloneView = MyView.extend({ // Stuff for CloneView }); var my_view = new CloneView({ el: $("#id") });

Upvotes: 0

Rida BENHAMMANE
Rida BENHAMMANE

Reputation: 4129

You can't just clone your view and use it the way you want, because there's a lot of work done in the background, like :

  • cid generation : unique id of your view in your application.
  • $el generation : the view main DOM element
  • events delegation : the view events delegation

So if you insist in cloning your view, I will suggest you to create a clone of it var cloneView = $.extend(true, {}, view); that do what exactly new View do.

And as mu is too short suggested, event $.extend won't work.

So the best way to do it, is to instantiate a new View

Upvotes: 1

Related Questions