[英]How can I stop event propagation with Backbone.js?
Using a Backbone.js View, say I want to include the following events: 使用Backbone.js视图,说我想要包含以下事件:
events: {
'click a': 'link',
'click': 'openPanel'
}
How can I avoid openPanel to be fired when I click on a link. 单击链接时,如何避免触发openPanel。 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. 想想例如Twitter.com,以及推文/右侧面板中的链接。
I've been using e.stopImmediatePropagation();
我一直在使用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 jQuery 但那是因为我对jQuery很熟悉
The JQuery preventDefault
method would also be a good option. JQuery preventDefault
方法也是一个不错的选择。
window.LocationViewLI = Backbone.View.extend({
tagName: "li",
template: _.template('<a href="/locations/<%= id %>"><%= name %></a>'),
events: {
"click a": "handleClick"
},
handleClick: function(event) {
event.preventDefault();
console.log("LocationViewLI handleClick", this.model.escape("name") );
// debugger;
},
...
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. 在处理程序中,您需要利用jQuery的event.stopPropagation()方法。 For example: 例如:
link: function(event) {
//do some stuff here
event.stopPropagation();
}
Two other methods that might work for you: 另外两种可能对您有用的方法:
events: {
'click a': 'link',
'click *:not(a, a *)': 'openPanel'
}
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). 然后openPanel不会捕捉click
任何事件<a>
一个或孩子<a>
(如果你在你的图标<a>
标签)。
At the top of the openPanel
method, make sure the event target wasn't an <a>
: 在openPanel
方法的顶部,确保事件目标不是<a>
:
openPanel: function(event) {
// Don't open the panel if the event target (the element that was
// clicked) is an <a> or any element within an <a>
if (event && event.target && $(event.target).is('a, a *')) return;
// otherwise it's safe to open the panel as usual
}
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). 请注意,这两种方法仍然允许从其他地方调用openPanel
函数(例如,从父视图或此视图上的其他函数)。 Just don't pass an event
argument and it'll be fine. 只是不要传递一个event
参数,它会没事的。 You also don't have to do anything special in your link
function -- just handle the click event and move on. 您也无需在link
功能中执行任何特殊操作 - 只需处理单击事件并继续操作即可。 Although you'll probably still want to call event.preventDefault()
. 虽然您可能仍想调用event.preventDefault()
。
在“链接”功能中返回“false”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.