2

this is a working code, but I want to simplify - correct, improve the code

window.addEvent = function(elem,type,callback) {
    var evt = function(e) {
        e = e || window.event;
        return callback.call(elem,e);
    };
    var cb = function(e) { return evt(e); };
    elem.addEventListener(type,cb,false);
    return elem;
};
window.findParent = function(child,filter,root) {
    do {
        if( filter(child)) return child;
        if( root && child == root) return false;
    } while(child = child.parentNode);
    return false;
};
function on(type, target, callback) {
  window.addEvent(document.body, type, function(e) {
    var s = window.findParent(e.srcElement || e.target, function(elm) {
        return elm.classList.contains(target);
    },this);

    if( s && callback ) {
        callback(e)
    }
  });
}
on("click", "page-link", function(e){
 console.log("hey its working");
});

In this example, I update the pagination with fetch, and I have to bind addEventlistener to every page link. I am thinking about, If its there a way to resolve this with primise, or another cleaner way, using the latest techniques? (with pure Javascript)

user348246
  • 380
  • 4
  • 16
  • SO is for getting help with code that isn't working. This should go to [https://codereview.stackexchange.com/](Code Review). Move it over there and you should get some help. – samanime Jan 29 '18 at 21:12
  • I'm voting to close this question as off-topic because it belongs on Code Review StackExchange. – samanime Jan 29 '18 at 21:12
  • @samanime This question is actually on-topic here. Just because it is on-topic at Code Review does not make it off-topic here. This is a question about a specific program, boiled down to a manageable chunk, and is perfectly welcome here. – Patrick Roberts Jan 29 '18 at 21:14
  • No, promises cannot be used for handling events that occur multiple times. If at all, you're looking for an EventStream abstraction. – Bergi Jan 29 '18 at 21:17
  • If you want to simplify, I'd recommend to omit useless stuff like `var cb = function(e) { return evt(e); };`. – Bergi Jan 29 '18 at 21:17
  • @PatrickRoberts "Cleaner ways" to do things are generally opinion-based, and are generally considered ill-suited for SO. It'd be better suited to Code Review, where discussion and opinions are more welcome. – samanime Jan 29 '18 at 21:18
  • You also don't need `window.event`. – SLaks Jan 29 '18 at 21:19
  • 2
    @samanime by that argument, [your question](https://stackoverflow.com/q/48039367/1541563) should be on Code Review instead. – Patrick Roberts Jan 29 '18 at 21:21
  • @Bergi what do you mean "EventStream abstraction" ? Can you explain, or provide some info? – user348246 Jan 29 '18 at 21:49
  • @almostokey Have a look at http://baconjs.github.io/ for example. There are many more FRP libraries with similar capabilities based on the same fundamental concepts, though – Bergi Jan 29 '18 at 21:58

0 Answers0