How do I get the 'this' element in Backbone click event?

2k views Asked by At

When I click something, I'd like to do something to that element (i.e. add a class), though I don't believe that this 'this' element in my event handler is actually that element. Here is a sample bit of my code:

var ApplicationRouter = Backbone.Router.extend({

    routes: {
        "": "home",
        "firstthing": "firstthing",
    },

    firstthing: function() {
        $(this).addClass('active');
    }
});

var ApplicationView = Backbone.View.extend({

    el: $('body'),

    events: {
        'click #something': 'displayFirstThing'
    },

    initialize: function(){
        this.router = new ApplicationRouter();
        Backbone.history.start();
    },

    displayFirstThing: function(){
        this.router.navigate("firstthing", true);
    },
});

new ApplicationView();

I'm wanting to add the class of 'active' to #something. I'll have more events that will have different classes etc, but looking to get some of the basics down now.

Also, accepting any suggestions on code structure!

2

There are 2 answers

0
Bart Jedrocha On BEST ANSWER

Backbone passes the event object as the first argument to the callback from which you can use the currentTarget property to work with the element that received the event. E.g.

var ApplicationView = Backbone.View.extend({

    el: $('body'),

    events: {
        'click #something': 'displayFirstThing'
    },

    // ... other code

    displayFirstThing: function( event ){
        $( event.currentTarget ).addClass( 'active' );
    },
});
1
VJAI On

I would suggest to store the elements that you want to access in view properties.

i.e.

var ApplicationView = Backbone.View.extend({

    el: $('body'),

    events: {
        'click #something': 'displayFirstThing'
    },

    render: function() {
      // render the view
      // store the link element in a property
      this.$something = this.$('#something');
    },

    displayFirstThing: function(){
        this.$something.addClass('someclass');
    },
});