Inside my Backbone views, in the initialize
function I do stuff like:
initialize: function () {
$(this.el).on('click', '.button', function () {
$(this).fadeTo(0.5);
}
}
This seems to go against Backbone's convention of using events
. Rewriting with the events
hash:
events: { 'click .button': 'fadeButton' },
fadeButton: function () {
$(this).fadeTo(0.5);
}
The problem is inside fadeButton
's scope the value of this
is not the same as when using .on()
. What is the correct way of doing this using the events
hash?
Like paul said, Backbone automatically sets the context for event callbacks to the view itself. So this
in the callback will be the view instance.
So you can get the effect you intend by using the view's scoped selector function...
events: {
'click .button': 'fadeButton'
},
fadeButton: function () {
this.$('.button').fadeTo(0.5);
}
... but if you've got multiple elements with class "button"
in your view, that'll fade all of them, in which case you can always use the event object that jQuery gives you to get the event target:
fadeButton: function (event) {
$(event.target).fadeTo(0.5);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With