MooTools版本的jQuery命名空间事件?

时间:2011-08-28 09:32:40

标签: jquery javascript-events namespaces mootools

jQuery允许你做像

这样的事情
$div.bind('click.namespace', function)
$div.unbind('click.namespace')

MooTools中有没有相应的内容?我尝试定义pseudo event

Event.definePseudo('shim', function(split, fn, args) {fn.apply(this, args);})

document.body.addEvent('click', function(){alert('regular click');});
document.body.addEvent('click:shim', function(){alert('shim click');});

document.body.removeEvents('click') // removes both!
document.body.removeEvents('click:shim') // removes neither!

这似乎是一个死胡同。

1 个答案:

答案 0 :(得分:3)

我使用Element.implement实现了它,但我的问题是要求使用原生的MooTools方法来完成它,而不是定义我自己的函数。

Element.implement({
    // Call as element.bind('event.namespace', function() {});
    bind: function(name, funktion) {
        // Get event type and namespace
        var split = name.split('.'),
            eventName = split[0],
            namespace = split[1];

        // Store the event by its full name including namespace
        this.bindCache = this.bindCache || {};

        if(this.bindCache[name]) {
            this.bindCache[name].push(funktion);
        } else {
            this.bindCache[name] = [funktion];
        }

        // Bind the function to the event
        this.addEvent(eventName, funktion);
    },

    // Call as element.unbind('event.namespace');
    unbind: function(name) {
        // Unbind the specified event
        var eventName = name.split('.')[0],
            funktions = this.bindCache[name],
            x = 0,
            funktion;

        for(; funktion = funktions[x++]; ) {
            this.removeEvent(eventName, funktion);
        }
    }
});

document.body.bind('click.1', function() {alert('click 1');});
document.body.bind('click.1', function() {alert('click 1 other');});
document.body.bind('click.2', function() {alert('click 2');});

document.body.unbind('click.1'); // leaves click.2