\$\begingroup\$
\$\endgroup\$
5
I'm looking for a way to shrink this down. It'not anything special or unique but I feel the repetitive nature of the code could lend itself to a sleeker and more functional refactoring.
$.e = {
doc: { ready:[], custom:[] },
win: { scroll:[], scrollstart:[], scrollstop:[], load:[], resize:[], resizestart:[], resizestop:[], orientationchange:[] }
};
$(window).on({
load:function(){for(var i = 0; i < $.e.win.load.length; i++){ $.e.win.load[i](); }},
scroll:function(){for(var i = 0; i < $.e.win.scroll.length; i++){ $.e.win.scroll[i](); }},
scrollstart:function(){for(var i = 0; i < $.e.win.scrollstart.length; i++){ $.e.win.scrollstart[i](); }},
scrollstop:function(){for(var i = 0; i < $.e.win.scrollstop.length; i++){ $.e.win.scrollstop[i](); }},
resize:function(){for(var i = 0; i < $.e.win.resize.length; i++){ $.e.win.resize[i](); }},
resizestart:function(){for(var i = 0; i < $.e.win.resizestart.length; i++){ $.e.win.resizestart[i](); }},
resizestop:function(){for(var i = 0; i < $.e.win.resizestop.length; i++){ $.e.win.resizestop[i](); }},
orientationchange:function(){for(var i = 0; i < $.e.win.orientationchange.length; i++){ $.e.win.orientationchange[i](); }}
});
Simon Forsberg
59.8k9 gold badges160 silver badges312 bronze badges
1 Answer 1
\$\begingroup\$
\$\endgroup\$
4
Use one event listener that propagates the event.
The correct collection of listeners in $.e.win is selected with event.type.
$.each($.e.win, function(eventName) {
$(window).on(eventName, propagateEvent);
});
function propagateEvent(event) {
var listeners = $.e.win[event.type];
for (var i = 0; i < listeners.length; i++) {
listeners[i].call(this, event);
}
}
answered Jul 8, 2017 at 10:11
woxxom
2,0021 gold badge10 silver badges12 bronze badges
-
\$\begingroup\$ Nice approach, the events are defined as an array at the beginning of the document as a $.e variable. \$\endgroup\$googabeast– googabeast2017年07月08日 14:14:04 +00:00Commented Jul 8, 2017 at 14:14
-
\$\begingroup\$ @googabeast, in that case the event subscription may be shortened, see the updated answer. \$\endgroup\$woxxom– woxxom2017年07月08日 14:19:39 +00:00Commented Jul 8, 2017 at 14:19
-
\$\begingroup\$ I was also thinking of the same solution. Why not use
eachinstead offor?. \$\endgroup\$Tushar– Tushar2017年07月08日 14:24:11 +00:00Commented Jul 8, 2017 at 14:24 -
\$\begingroup\$ @Tushar, because without ES2015 arrow syntax there's no gain in clarity \$\endgroup\$woxxom– woxxom2017年07月08日 14:41:34 +00:00Commented Jul 8, 2017 at 14:41
You must log in to answer this question.
default
$.e? \$\endgroup\$$.each($.e.win, function(_k,_v){ $(window).on(_k, function(){ for(var i = 0; i < $.e.win[_k].length; i++){ $.e.win[_k][i](); }; }) });\$\endgroup\$