Skip to content

ko.cleanNode inconsistency #2314

@flasaracina

Description

@flasaracina

When I use knockout without jQuery and I call ko.cleanNode on my template, I expect knockout to remove all the event listeners from it just as if I am using jQuery (for consistency reasons). Sadly this is not the case, in fact without using jQuery all the event listeners attached to my template are still there.

Looking at the code I found that the "registerEventHandler" function actually removes all the event listeners but only on IE or when jQuery is being used.

the code is as follows:

if (!ko.options['useOnlyNativeEvents'] && !mustUseAttachEvent && jQueryInstance) {
    jQueryInstance(element)['bind'](eventType, wrappedHandler);
} else if (!mustUseAttachEvent && typeof element.addEventListener == "function")
    element.addEventListener(eventType, wrappedHandler, false);
else if (typeof element.attachEvent != "undefined") {
    var attachEventHandler = function (event) { wrappedHandler.call(element, event); },
        attachEventName = "on" + eventType;
    element.attachEvent(attachEventName, attachEventHandler);

    // IE does not dispose attachEvent handlers automatically (unlike with addEventListener)
    // so to avoid leaks, we have to remove them manually. See bug #856
    ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
        element.detachEvent(attachEventName, attachEventHandler);
    });
} else
    throw new Error("Browser doesn't support addEventListener or attachEvent");

It should be :

if (!ko.options['useOnlyNativeEvents'] && !mustUseAttachEvent && jQueryInstance) {
    jQueryInstance(element)['bind'](eventType, wrappedHandler);
} else if (!mustUseAttachEvent && typeof element.addEventListener == "function"){
    element.addEventListener(eventType, wrappedHandler, false);
    ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
        element.removeEventListener(eventType, wrappedHandler);
    });
}else if (typeof element.attachEvent != "undefined") {
    var attachEventHandler = function (event) { wrappedHandler.call(element, event); },
        attachEventName = "on" + eventType;
    element.attachEvent(attachEventName, attachEventHandler);

    // IE does not dispose attachEvent handlers automatically (unlike with addEventListener)
    // so to avoid leaks, we have to remove them manually. See bug #856
    ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
        element.detachEvent(attachEventName, attachEventHandler);
    });
} else
    throw new Error("Browser doesn't support addEventListener or attachEvent");

I hope that you coud fix this one asap.

Thank you

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions