I have a Backbone app and we have stuff like this:
render: function() {
this.$el.html(_template());
$('#id').plugin();
return this;
}
The #id is from an element that’s being rendered. This only works sometimes, as it can take longer for it to actually insert into dom.
Is there a way within this view, to define a callback or somehow know for sure that the dom has been updated, before calling our plugin() function?
Thank you!
Your problem is that this:
is looking for
#idinside the DOM butthis.$elisn’t in the DOM yet; so, if#idis insidethis.$el, then#idisn’t in the DOM either and$('#id')will be empty. You want to look for#idinsidethis.$eland Backbone provides thethis.$shortcut for that:So you want to do this:
If your plugin needs its element to be rendered (perhaps it needs size and position information), then you’ll have to kludge around a bit:
setTimeout(..., 0)or_.deferto bind the plugin after the browser has updated the DOM. This only works if everyone is using the commonx.append(v.render().el)pattern though.