如何使用 Backbone.js 停止事件传播?
使用 Backbone.js 视图,假设我想包含以下事件:
events: {
'click a': 'link',
'click': 'openPanel'
}
如何避免在单击链接时触发 openPanel。我想要的是有一个可单击的框来触发一个操作,但是这个框可以包含应该触发其他操作的元素,而不是父操作。例如 Twitter.com 以及推文/右侧面板中的链接。
Using a Backbone.js View, say I want to include the following events:
events: {
'click a': 'link',
'click': 'openPanel'
}
How can I avoid openPanel to be fired when I click on a link. What I want is to have a clickable box which will trigger an action, but this box can have elements which should trigger other actions, and not the parent action. Think for example Twitter.com, and links in Tweets/right hand panel.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我一直在使用
e.stopImmediatePropagation();
来阻止事件传播。我希望有一种更短的方法来做到这一点。我想返回 false;但这是由于我对 jQuery 的熟悉I've been using
e.stopImmediatePropagation();
in order to keep the event from propagating. I wish there was a shorter way to do this. I would like return false; but that is due to my familiarity with jQueryJQuery
preventDefault
方法也是一个不错的选择。The JQuery
preventDefault
method would also be a good option.每个事件处理程序在触发时都会传递一个事件对象。在处理程序内部,您需要利用 jQuery 的 event.stopPropagation() 方法。例如:
Each of your event handlers will be passed an event object when it's triggered. Inside your handler, you need to leverage jQuery's event.stopPropagation() method. For example:
其他两种可能适合您的方法:
1
openPanel 将不会捕获任何
或
子级上的
click
事件。 code> (如果您的标记中有图标)。
2
在
openPanel
方法的顶部,确保事件目标不是:
请注意,这两种方法仍然允许
openPanel
函数从其他地方调用(例如,从父视图或该视图上的另一个函数)。只要不传递event
参数就可以了。您也不必在link
函数中执行任何特殊操作 - 只需处理点击事件并继续。尽管您可能仍想调用event.preventDefault()
。Two other methods that might work for you:
1
Then openPanel will not capture
click
events on any<a>
or child of an<a>
(in case you have an icon in your<a>
tag).2
At the top of the
openPanel
method, make sure the event target wasn't an<a>
:Note that both of these methods still allow the
openPanel
function to be called from elsewhere (from a parent view or another function on this view, for example). Just don't pass anevent
argument and it'll be fine. You also don't have to do anything special in yourlink
function -- just handle the click event and move on. Although you'll probably still want to callevent.preventDefault()
.在“link”函数中返回“false”。
Return "false" in your "link" function.