I’ve got this piece of HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Backbone.js Demos</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.6/underscore-min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
<script src="app.js"></script>
<script type="x-tmpl" id="list_tmpl">
<span><%= part1 %><%= part2 %></span>
<a href="#swappy" class='swap'>[SWAP]</a>
<span> </span>
<a href="#del" class='remove'>[DELETE]</a>
</body>
</html>
When the script tags are between the body tags, my scripts work properly. However, if I move all of my script tags to the head, they cease working. I’m baffled as to why. Is there any reason for this behaviour? Thank you all for your time and help!
EDIT: APP
(function($){
Backbone.sync = function (method, model, success, error){
success();
};
var Item = Backbone.Model.extend({
defaults: {
part1: 'Hello',
part2: 'World'
}
});
var ItemList = Backbone.Collection.extend({
model: Item
});
var ItemView = Backbone.View.extend({
tagName: 'li',
events: {
'click .swap': 'swap',
'click .remove': 'remove'
},
initialize: function(){
_.bindAll(this, 'render', 'unrender', 'swap', 'remove');
this.model.bind('change', this.render);
this.model.bind('remove', this.unrender);
},
render: function(){
$(this.el).html(_.template($('#list_tmpl').html(), this.model.toJSON()));
return this;
},
unrender: function(){
$(this.el).remove();
},
swap: function(){
var swapped = {
part1: this.model.get('part2'),
part2: this.model.get('part1')
};
this.model.set(swapped);
},
remove: function(){
this.model.destroy();
}
});
var AppView = Backbone.View.extend({
el: $('body'),
events: {
'click #add': 'addItem'
},
initialize: function (){
this.counter = 0;
_.bindAll(this, 'render', 'addItem', 'appendItem');
this.collection = new ItemList();
this.collection.bind('add', this.appendItem);
this.render();
},
render: function(){
$(this.el).append("<button id='add'>Add Item</button>");
$(this.el).append("<ul id='todoList'/>");
},
addItem: function(){
this.counter++;
var item = new Item();
item.set({
part2: item.get('part2') + this.counter
});
this.collection.add(item);
},
appendItem: function(item){
var itemView = new ItemView({
model: item
});
$('#todoList', this.el).append(itemView.render().el);
}
});
var Tasker = new AppView();
})(jQuery);
This behavior happens when the js file uses the body once it’s loaded, so they must be embedded within body.
you can put jquery,json and underscore files in the head.
Other files, you must check if they don’t call the body when they are loaded.