Reputation: 1141
Mates, I've got the following code:
App.Views.Bed = Backbone.View.extend({
tagName: 'li',
template: _.template( App.Templates.Bed ),
events: {
'click .booked': 'showReservation',
'click .occupied': 'showGuest',
'click .free': 'checkIn'
},
render: function(){
if( this.model.get('id_bookings') ){
this.clase = 'booked';
}
if( this.model.get('id_guests') ){
this.clase = 'occupied';
}else{
this.clase = 'free';
}
this.$el.addClass(this.clase).html( this.template( this.model.toJSON() ) );
return this;
},
checkIn: function(){
console.log('Check-in form load');
},
showReservation: function(){
},
showGuest: function(){
}
});
I'm trying to trigger a different method depending on the className (which I set depending on the content's model).
Is there a way to filter by classes when defining a view's events?
Thanks!
Upvotes: 0
Views: 740
Reputation:
Keep it simple. You just need to set one click handler for your button and let it proxy to the right method.
App.Views.Bed = Backbone.View.extend({
tagName: 'li',
template: _.template( App.Templates.Bed ),
events: {
'click': 'click_handler'
},
render: function(){
if( this.model.get('id_bookings') ){
this.clase = 'booked';
}
if( this.model.get('id_guests') ){
this.clase = 'occupied';
}else{
this.clase = 'free';
}
this.$el.addClass(this.clase).html( this.template( this.model.toJSON() ) );
return this;
},
click_handler: function() {
if (this.$el.hasClass('booked')) {
this.showReservation();
} else if (this.$el.hasClass('occupied')) {
this.showGuest();
} else if (this.$el.hasClass('free')) {
this.checkIn();
} else {
// oops!?
}
},
checkIn: function(){
console.log('Check-in form load');
},
showReservation: function(){
},
showGuest: function(){
}
});
Upvotes: 1
Reputation: 35950
In short, it's not possible using the declarative events
hash, unless you're willing to do some :parent
selector hacks, and I'm not sure if that's even possible, either.
The problem is that any jQuery selector you use to define the element (for example the class selector .booked
) is applied within the view´s el
, so the element's own class is not considered in the selector.
Instead I would dynamically set the handler method. Something like:
events: {
'click': 'onClick'
},
render: function(){
if( this.model.get('id_bookings') ){
this.clase = 'booked';
this.onClick = this.showReservation;
}
if( this.model.get('id_guests') ){
this.clase = 'occupied';
this.onClick = this.showGuest;
}else{
this.clase = 'free';
this.onClick = this.checkIn;
}
_.bindAll(this, 'onClick');
this.$el.addClass(this.clase).html( this.template( this.model.toJSON() ) );
return this;
},
Upvotes: 1