简体   繁体   中英

Cant use a closure as event listener to pushState

I want to use a closure as an eventlistener (im working on a routing library), so i created a class that does exactly that

'use strict';
var RouteManager = RouteManager || {};

RouteManager.OnClickDelegate = function(UrlHandler)
{
    var handler = UrlHandler;

    return function delegate(e)
    {
        e = e ||  window.event;
        var element = e.target || e.srcElement;
        if (element.tagName == 'A') {
            console.log("link click");
            window.history.pushState({},"",e.href);
            //this.handler.handle(element.href);
            return false;
        }
    };
};

assignment:

document.onclick = RouteManager.OnClickDelegate(new UrlHandler());

However, although assigning the closure as an event listener works ("link click" is logged correctly) the state isnt pushed

to make matters even stranger, this works correctly:

document.onclick = (function(UrlHandler){
    var uh = UrlHandler;
    return function delegate(e)
    {
        e = e ||  window.event;
        var element = e.target || e.srcElement;
        if (element.tagName == 'A') {
            console.log("link click");
            window.history.pushState({},"",e.href);
            //this.handler.handle(element.href);
            return false;
        }
    };
})(new UrlHandler());

Any ideas?

Also, please dont suggest a working routing library, its not what im asking for

the state isnt pushed

Probably because e.href is undefined . You want element.href .


Notice that in your closure you can use the parameter variable directly, you don't need that local variable declaration. Just use this:

RouteManager.OnClickDelegate = function(handler) {
    return function delegate(e) {
        e = e ||  window.event;
        var element = e.target || e.srcElement;
        if (element.tagName == 'A') {
            console.log("link click");
            window.history.pushState({}, "", element.href);
            handler.handle(element.href);
            return false;
        }
    };
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM