Reputation: 5258
I've been learning backbone.js and put up some code together finally. Everything is on a fiddle here.
The problem precisely is, I think with the events
. They aren't triggering the view functions on click
.
How to make it work? Am I missing any 'gotchas'?
Upvotes: 2
Views: 164
Reputation: 8581
For extra credit and to make things more interesting :-) , you don't actually NEED to have a clearly defined el
for the Backbone.View to delegate your events properly. Take this for example:
MyView = Backbone.View.extend({
// The events to delegate
events: {
'click #test':'onClick'
},
initialize: function() {
// delegateEvents() actually happens in constructor, before render()
// At this point there is no #test
},
render: function() {
// By default, el is an empty div
this.$el.html('<button id="test">testButton</button>');
return this;
},
onClick: function(event) {
console.log('clicked');
}
});
view = new MyView();
$('body').append(view.render().el); // We append this view to end of body
In the previous code, we didn't (explicitly) define an el
. The most important thing to remember isn't that you have an explicit el
. Rather, it's what @jakee says here:
Views listen to events that emerge from the DOM element that it is bound to.
The event hash you pass in or define inside a View are listened for within the view. Whether that is a defined el
or the generic div, it listens for stuff inside it and since it delegates the event handlers, the handlers continue to point to this
view. Nice.
If you did something like this:
$('#test').remove();
$('body').prepend('<button id="test">Second Test</button>');
We find that the #test is now outside of our view (the generic el that is appended at the end of our body. Clicking it does... nothing. But the coolest thing is this.
$('#test').remove();
$('div:last').html('<button id="test">Third Test</button>');
With this code we removed the #test at the top of the body and added it back into the view. Clicking it, will resume it's onClick()
functionality.
Upvotes: 1
Reputation: 18556
Views listen to events that emerge from the DOM element that it is bound to.
You havent bound your view to any element. Which means that the view's element is an empty div
that really isn't placed anywhere. So the events never reach the view. What you need to do is to bind the view to an element that hears the events coming from the buttons.
So set the view's el
so that it encompasses the buttons as well and voilà!
Upvotes: 3
Reputation: 102723
You need to define the container of the view by setting the el
property, then it works as expected.
Backbone.View.extend({
el: "body",
events: {
"click #add-contact": "addContact",
"click #test": "alertMe"
},
Updated Fiddle: http://jsfiddle.net/fAB28/1/
Upvotes: 1