I have a view in a .js file apart the ‘index.html’ file which looks like this :
window.App = Backbone.View.extend({
el: $('#article'),
initialize: function() {
_.bindAll(this, 'render');
console.log('binding');
console.log($('#article'));
this.render();
},
render: function() {
console.log('rendering');
this.$el.html("rendered");
return this;
}
});
I am allocating this view in ‘index.html’ using JQuery’s ready function :
<div id="article">
</div>
<script type="text/javascript">
$(function(){
console.log($('#article'));
new window.App();
});
</script>
As you may guess, “rendered” doesn’t appear on the DOM. The problem is that when i pack everything together (the view and the allocation in the tag), it works.
Any ideas ?
I think your problem is that this:
happens before this HTML:
is seen by the browser. That would leave
$('#article')empty and yourrendermethod wouldn’t have access to anything in the DOM. Open your console and run this demo and you’ll see what you’re seeing: http://jsfiddle.net/ambiguous/7sGcZ/The easiest solution is to use the selector as
el:and let Backbone turn it into a DOM element on its own. That way,
$('#article')will find something when Backbone needs to create the view’s$el.Demo (that works): http://jsfiddle.net/ambiguous/Vd6jP/