I have followed numerous screen casts as well as trawled the backbone docs extensively and I cannot figure out why my view events are not being fired. My (short) code for testing is as follows:
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="js/underscore.min.js"></script>
<script type="text/javascript" src="js/backbone.min.js"></script>
<script type="text/javascript">
var App = (function($){
var NavigationItemView = Backbone.View.extend({
el: '#navigation',
initialize: function(params){
this.label = params.label;
this.appendTo = params.appendTo;
},
events: {
"click #add" : "test"
},
test: function(){
$(this.el).html("<li>Testing...</li>");
},
render: function(){
$(this.el).html("<li><a href=\"#\">"+this.label+"</a></li>");
}
})
var self = {};
self.init = function(){
new NavigationItemView({ label: 'Test Nav Label' });
}
return self;
});
$(document).ready(function(){
App(jQuery).init();
})
</script>
If I change the init method code from this:
new NavigationItemView({ label: 'Test Nav Label' })
To this:
new NavigationItemView({ label: 'Test Nav Label' }).render()
The render method is called perfectly, indicating there is no issues with the set up of the view. I can replace render()
with test()
and likewise it works.
However, the event of clicking on the link with ID #add does not fire the test even, and surely it should? To clarify, I do have a link with id 'add' in the DOM, I have checked and checked again.
If I add event hooks using jQuery and fire off certain methods of the view manually, that works. It's backbones own event hooks that are not working for me.
I have looked at the related posts, and most of the suggestions were use the el property, which I have. #navigation
is an empty <ul>
in my case. I have changed it to a div but with no change in behaviour.
All help much appreciated.
Is your #add element a child of your view element (#navigation)? Events are fired only on children elements of you view "el". For instance, this will not work:
<div id="navigation">
...
</div>
<div id="add">
...
</div>
While this will:
<div id="navigation">
...
<div id="add">
...
</div>
...
</div>