Categories
Javascript Programming Web

Backbone dynamic elements

I recently discovered Backbone’s setElement function. What it allowed me to do was dynamically create a view’s container in Javascript and transfer/assign the view and its events to the new element.

Using jQuery within the view initialize event:

this.el = $('<div id="\'newView\'"></div>'); 
this.setElement(this.el); 
$('#content').append(this.el);

I manipulated the this.el attribute directly, without using an interim variable, it seemed to work ok, but if there are side-effects I discover later, it should be easy enough to change. setElement will automatically assign its argument to this.el so nothing further needs to be done.