Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

jquery - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...