Eugene Yu
Eugene Yu

Reputation: 3958

dojo how to overwrite event handler

Currently dojo uses on method to connect event to handler.

btn = new Button();
btn.on('click', function () {console.log('do something');});

this will call the attached function when the button gets clicked.

however, according to the documents, removing existing handlers should be done in the following way

handler = btn.on('click', function () {console.log('do something');});
handler.remove();

this is not the way I want to remove event handler.

I do not store the handler reference anywhere. But I want to add a new 'click' event by doing

btn.on('click', function () {console.log('do something different');});

so that it replaces the existing 'click' event handler and add a new one.

Is there any way to achieve what I want?

Thanks!

Upvotes: 0

Views: 1202

Answers (2)

Dimitri Mestdagh
Dimitri Mestdagh

Reputation: 44665

That's not possible, the framework tells you to do it in the way by creating a reference to the event handler. This is similar to how other frameworks like jQuery work.

jQuery has of course a mechanism to remove all event handlers by using the off() function, but that's not available in Dojo either. Like Chris Hayes suggested in the comments, you can implement such a feature by yourself, either by wrapping it inside another module, or by using aspects on the dojo/on module.

For example, you can wrap it inside a new module:

// Saving the event handlers
var on2 = function(dom, event, callback) {
    on2.handlers = [];

    if (on2.handlers[event] === undefined) {
        on2.handlers[event] = [];   
    }
    var handler = on(dom, event, callback);
    on2.handlers[event].push({
        node: dom,
        handler: handler
    });
    return handler;
};
// Off functionality
lang.mixin(on2, on, {
    off: function(dom, event) {
        if (this.handlers[event] !== undefined) {
            array.forEach(this.handlers[event], function(handler) {
                if (handler.node === dom) {
                    handler.handler.remove();   
                }
            });
        }
    }
});

And then you can use it:

on2(dom.byId("test"), "click", function() {
    console.log("test 1 2 3"); // Old event handler
});
on2.off(dom.byId("test"), "click"); // Remove old event handlers
on2(dom.byId("test"), "click", function() {
    console.log("test 4 5 6"); // New event handler
});

This should work fine, as you can see in this fiddle: http://jsfiddle.net/X7H3F/

Upvotes: 2

AdityaParab
AdityaParab

Reputation: 7100

btn = new Button();
btn.attr('id','myButton');
query("#myButton").on('click', function () {console.log('do something');});

Do the same thing when you want to replace your handler. Like,

query("#myButton").on('click', function () {console.log('do something different');});

Hope that helps :)

Upvotes: -1

Related Questions