2014-05-25 22 views
2

我正在尝试为允许用户注入JavaScript的平台创建脚本。他们正在使用YUI,特别是将事件附加到按钮上。我想拦截这个按钮,但我不知道如何停止,阻止,移除或以其他方式阻止事件处理程序发起。如何删除YUI委托事件?

注:我没有()由`Y.delegate返回的处理程序直接访问

到目前为止,我已经试过

Y.detachAll('click'); 
Y.unsubscribeAll('click'); 
Y.one('body').detachAll('click'); 
Y.one('body').unsubscribeAll('click'); 
Y.one('.the-delegated-class').detachAll('click'); 
Y.one('.the-delegated-class').unsubscribeAll('click'); 

一切都无济于事。实际上,我唯一的成功就是完全删除并替换主体HTML,它明显地将所有事件处理程序与它相结合,而不仅仅是我想要删除的那个。

任何见解?

+0

该平台不是任何偶然的方格,是吗? :P – cregox

+1

@Cawas是的,不知道为什么我这么模糊......: -/ – KTastrophy

+0

相当的话,我使用'destroy(true)':http://stackoverflow.com/a/9405055/ 274502 – cregox

回答

1

原来我尝试之一是正确的方法,但我的用法是错误的。我(在不知不觉中)试图在事件首先被附加之前将事件分开。

,在的情况下,说: Y.one('body).delegate('click',...)

这工作: Y.one('body').detach('click')

虽然理想情况下你会打电话直接分离由委托调用返回的EventHandle。

0

委托事件方法似乎无法将句柄存储在任何位置,您可能可以为Event.delegate创建补丁替换,该替换存储针对委托元素的句柄。修补YUI的一个基本的例子:https://gist.github.com/tivac/1424351

未经测试的代码:

var config = { 
    groups : { 
     patches : { 
      base : "/js/patches/", 
      modules : { 
       "node-event-delegate-patches" : { 
        path : "node-event-delegate.js", 
        condition : { 
         name : "node-event-delegate-patches", 
         trigger : "node-event-delegate", 
         test : function() { return true; } 
        } 
       } 
      } 
     } 
    } 
}; 

YUI.add("node-event-delegate-patches", function(Y) { 
    var L = Y.Lang; 

    Y.Node.prototype.delegate = function(type) { 
     var args = Y.Array(arguments, 0, true), 
      handle, 
      index = (L.isObject(type) && !L.isArray(type)) ? 1 : 2; 
     args.splice(index, 0, this._node); 

     if (!L.isArray(this._node._delegate_event_handles)){ 
      this._node._delegate_event_handles = []; 
     } 
     handle = Y.delegate.apply(Y, args); 
     this._node._delegate_event_handles.push(handle); 
     return handle; 
    }; 

    Y.Node.prototype.detachDelegates = function(){ 
     Y.Array.each(this._node._delegate_event_handles, function(handle){ 
      handle.detach(); 
     }); 
    } 
});