Backbone.js 事件绑定
我正在使用 Backbone.js,它为每个模型的视图提供分段的控件类型 UI 元素。它们每个都由一个 ul 和一些 li 元素组成。我想绑定一个事件,以便当单击这些元素之一时,我可以确定单击了哪个元素并使用适当的值更新模型。
问题在于 Backbone 绑定事件(这些事件位于视图的事件哈希中),以便回调函数中的“this”引用视图,而不是 li 元素。这意味着我无法确定这几个 li 元素中的哪一个被单击了。如果我使用普通的 jQuery 绑定,我可以将“this”绑定到 li 元素,但是我不再跟踪模型,所以我无法更新它。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在我看来,jQuery 将
this
设置为当时方便的任何内容的习惯是一种非常令人讨厌的模式 - 幸运的是,您永远不必依赖它:...您可以使用 <事件对象的 code>target 或
currentTarget
(视情况而定)。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:... You can use the
target
orcurrentTarget
of the event object, as appropriate.不明白为什么我不能对上面@jashkenas 的答案发表评论。他的方法是正确的(谢谢!),但我想我应该澄清一下情况:在您的事件处理程序中,您可以恢复事件绑定到的元素。示例骨干代码如下所示:
我使用它在所有表单字段中设置默认文本...是的,我还不太喜欢 HTML5 :)
编辑:
顺便说一句,e.target 是原始元素。您需要使用 $(e.target) 来获取 jQuery 访问权限。
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:
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.