Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translating the `on` pattern to Backbone's `event` hash

Tags:

backbone.js

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 image 356
Randomblue Avatar asked Dec 28 '11 21:12

Randomblue


1 Answers

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);
}
like image 200
satchmorun Avatar answered Oct 24 '22 03:10

satchmorun