Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.