Backbone.js Event Binding

2019-01-10 21:15发布

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.

2条回答
Fickle 薄情
2楼-- · 2019-01-10 21:48

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.

查看更多
forever°为你锁心
3楼-- · 2019-01-10 21:55

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.

查看更多
登录 后发表回答