Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
Backbone.js Event Binding

I'm using Backbone.js have a segmented control-type UI element for each model's view. They are each made up of a ul with a few li elements. I want to bind an event such that when one of these elements is clicked, I can determine which one has been clicked and update the model with the appropriate value.

The problem is that Backbone binds the events (these are in the events hash of the view) such that "this" in the callback function refers to the view, not the li elements. This means that I can not determine which of the several li elements has been clicked. If I used a normal jQuery binding, I can have "this" bound to the li elements, but then I don't have track of the model anymore, so I can't update it.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

jQuery's habit of setting this to whatever happens to be convenient at the time is a pretty nasty pattern, in my opinion -- fortunately, you never have to rely on it:

onClick: function(e) {
  this;                // Still the view instance (as it should be).
  e.target;            // The element that was clicked.
  e.currentTarget;     // The element that was bound by the click event.
}

... You can use the target or currentTarget of the event object, as appropriate.

over 4 years ago · Santiago Trujillo Report

0

Can't figure out why I can't comment on @jashkenas answer above. His method is correct (thank you!) but I thought I'd clarify the situation: in your event handler, you can recover the element that the event was bound to. Sample backbone code would look like this:

MyView = Backbone.View.extend({
    events: {
        'click .item': 'handleClick'
    },

    handleClick: function(e) {
        this; // The view instance
        e.target; // The element that was clicked 
        e.currentTarget; // The element that was bound by the click event
    }
});

I use this to setup default text in all of my form fields...yeah I'm not much into HTML5 yet :)

Edit: Btw, e.target is the raw element. You'll need to use $(e.target) to get jQuery access.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!