Backbone.js 事件绑定 [英] Backbone.js Event Binding

查看:31
本文介绍了Backbone.js 事件绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Backbone.js,每个模型的视图都有一个分段的控件类型 UI 元素.它们每个都由一个带有几个 li 元素的 ul 组成.我想绑定一个事件,这样当这些元素之一被点击时,我可以确定哪个元素被点击并用适当的值更新模型.

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.

问题在于 Backbone 绑定事件(这些在视图的事件哈希中),因此回调函数中的this"指的是视图,而不是 li 元素.这意味着我无法确定点击了几个 li 元素中的哪一个.如果我使用普通的 jQuery 绑定,我可以将this"绑定到 li 元素,但是我不再跟踪模型,所以我无法更新它.

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.

推荐答案

jQuery 将 this 设置为当时方便的任何方式的习惯是一种非常讨厌的模式,在我看来 - 幸运的是,您永远不必依赖它:

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

... 您可以根据需要使用事件对象的 targetcurrentTarget.

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

这篇关于Backbone.js 事件绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆