javascript - How to simulate namespaced events or unbind individual events WITHOUT jQuery? -


i have framework lazyloads ads when scrolled viewport. when page loads, check see in view , load them. if not in view, create scroll event , namespace each 1 can bind , unbind them individually:

if (adisinview("ad1") == false) {      $(document).on("scroll.ad1", function() {         if (adisinview("ad1") == true) {             displayad("ad1");             $(document).off("scroll.ad1");         }      }); } 

this way it's easy set scroll.ad1, scroll.ad2, etc., binding , unbinding them individually.

this only part of code dependent on jquery. don't want load 50 kb file can have namespaced events. how can using addeventlistener , removeeventlistener? can't use

window.removeeventlistener("scroll"); 

because unbind of scroll events, , namespacing ("scroll.ad1") doesn't exist natively.

i haven't found other posts on exact topic. i've heard few people mention jquery source code creates namespacing storing events in object, i'm not sure how works. ideas?

you can bind , unbind specific handlers.

if (adisinview("ad1") == false) {     var ad1_listener = function() {         if (adisinview("ad1") == true) {             displayad("ad1");             window.removeeventlistener("scroll", ad1_listener);         }      }     window.addeventlistener("scroll", ad1_listener); } 

you can go step further , do:

function register_ad(ad) {     function listener() {         if (adisinview(ad) === true) {             displayad(ad);             window.removeeventlistener("scroll", listener);         }      }     window.addeventlistener("scroll", listener); }  if (adisinview("ad1") === false) {     register_ad("ad1"); } 

Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -