2013-01-11 122 views
0

我试图阻止事件传播只针对特定的事件处理程序,同时允许在同一事件他人传播,这里有一个例子:停止JQuery的事件传播的特定事件处理

function Control(parent) { 
    this.Parent = $(parent); 
    this.Parent.append('<div class="test"></div>'); 
    this.Test = $('.test', this.Parent).last(); 
    this.Test.bind('mousedown', this, Control_All); 
    this.Test.bind('mousedown', this, Control_Top); 
} 
function Control_All(event) { 
    //this should bubble up through both c1 and c2 
} 
function Control_Top(event) { 
    //this should stop at c2 
} 
Control.prototype.constructor = Control; 
Control.prototype.All = Control_All; 
Control.prototype.Top = Control_Top; 

var c1 = new Control('body'); 
var c2 = new Control(c1.Test); 

在上面的例子c1.Test和c2.Test是相同的大小。我试图做一个mousedown事件调用这三个事件(我知道面向对象的方法没有被维护,状态通过event.data保存,但我使用OO表示法来简化,在我的实际使用案例All和单委托绑定变量的订单,只有在某些情况下,所以在它们所连接的顺序是无法控制的): c1.All c2.All c2.Single

我已经尝试event.preventDefault() ,event.stopPropagation(),event.stopImmediatePropagation(),并在Control_Top结尾处返回(false),但是没有一个可以像上面描述的那样工作。

编辑:Here is a JSFiddle Link帮助任何有兴趣的人帮助它。

再次编辑:如果有人需要,可以使用全局绑定和额外绑定到body.mousedown,here it is,欢迎使用不使用全局绑定或额外绑定的解决方案。

+0

这里只有一个 “事件” 发生。事件冒泡,而不是事件处理程序。如果您停止传播该事件,则它不会传播到任一处理程序。只要让你的处理程序更加具体,以便他们只在你希望他们处理的地方处理事件。 –

+0

凯文,我在你的回应之后解决了它,并且在编辑中发布了解决方案,在我的具体情况下,事件实际上受到来自两个不同点的控制的约束(一个内部应该起泡,另一个应该只被调用一次尽管事实上控件可以嵌套在彼此的内部,但是可以监听页面中的每个控件)。我提出的全球+额外绑定解决方案感觉有点笨拙,但它有效,我需要转到下一部分。 – CoryG

+0

这是你想要的吗? http://jsfiddle.net/cvmEz/1/ –

回答

3

只需确认事件目标等于您将事件绑定到的元素。

http://jsfiddle.net/cvmEz/2/

function Control(parent,name) { 
    this.Parent = $(parent); 
    this.Parent.append('<div class="test" data-name="' + name + '"></div>'); 
    this.Test = $('.test', this.Parent).last(); 
    this.Test.bind('mousedown', this, Control_All); 
    this.Test.bind('mousedown', this, Control_Top); 
} 
function Control_All(event) { 
    if (event.target == this) { 
    console.log(this.getAttribute('data-name') + '.All'); 
    } 
} 
function Control_Top(event) { 
    if (event.target == this) { 
    console.log(this.getAttribute('data-name') + '.Top'); 
    } 
} 
Control.prototype.constructor = Control; 
Control.prototype.All = Control_All; 
Control.prototype.Top = Control_Top; 

var c1 = new Control('body', 'c1'); 
var c2 = new Control(c1.Test, 'c2'); 

console.log('--------');