Translation of the `on` template to hash` event`

Inside the Backbone views in a function, initializeI do things like:

initialize: function () {
    $(this.el).on('click', '.button', function () {
        $(this).fadeTo(0.5);
    }
}

This seems to run counter to database use conventions events. Hash overwrite events:

events: { 'click .button': 'fadeButton' },
fadeButton: function () {
    $(this).fadeTo(0.5);
}

The problem is inside the area fadeButton, the value thisdoes not match the value .on(). What is the correct way to do this with eventshash?

+5
source share
2 answers

Like paul, Backbone automatically sets the context for event callbacks for the view itself. So thisthe callback will be an instance of the view.

, , , view...

events: { 
  'click .button': 'fadeButton' 
},

fadeButton: function () {
  this.$('.button').fadeTo(0.5);
}

... "button" , , , jQuery ,

fadeButton: function (event) {
  $(event.target).fadeTo(0.5);
}
+7

.

, Backbone . , this fadeButton - , .

, fadeButton.

fadeButton: function () {
  $(this.el).fadeTo(0.5);
}
0

All Articles