Skip to content

Instantly share code, notes, and snippets.

@msbrime
Created March 23, 2019 13:24
Show Gist options
  • Save msbrime/b9b510b248836b2c72776c7defcf3f04 to your computer and use it in GitHub Desktop.
Save msbrime/b9b510b248836b2c72776c7defcf3f04 to your computer and use it in GitHub Desktop.
A dispatcher for twbs/ratchet that fires events on page/route change
window.Dispatcher = (function(win){
var instance;
function init(){
var
callbackRegister = {},
pageCheck;
/**
* [registerCallback description]
* @param {string} page
* @param {Function} callback [description]
* @return void
*/
var registerCallback = function(page,callback){
callbackRegister[page] = callbackRegister[page] || [];
callbackRegister[page].push(callback);
return instance;
};
/**
* [registerCallbacks description]
* @param {[type]} page [description]
* @param {[type]} callbacks [description]
* @return {[type]} [description]
*/
var registerCallbacks = function(page,callbacks){
callbacks.forEach(function(callback){
registerCallback(page,callback);
});
return instance;
};
var fireCallbacksOn = function(events){
events.forEach(function(event){
win.addEventListener(event,function(){
fireCallbacks();
});
});
};
/**
* [setPageCheck description]
* @param {Function} fn [description]
*/
var setPageCheck = function(fn){
pageCheck = fn;
};
/**
* [fireCallbacks description]
* @return {[type]} [description]
*/
var fireCallbacks = function(){
for(var page in callbackRegister){
if(callbackRegister.hasOwnProperty(page)){
if(pageCheck(page)){
callbackRegister[page].forEach(function(callback){
callback();
});
}
}
}
};
return {
registerCallback : registerCallback,
registerCallbacks : registerCallbacks,
fireCallbacksOn : fireCallbacksOn,
setPageCheck : setPageCheck
};
}
return {
getInstance : function(){
if(!instance){
instance = init();
}
return instance;
}
};
})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment