Skip to content

Instantly share code, notes, and snippets.

@newbamboo

newbamboo/pusher_mock.js Secret

Created Oct 18, 2010
Embed
What would you like to do?
neat bit of code for spoofing events at random(ish) intervals
/* Abstract event binding
--------------------------------------------------------*/
var AbstractEventsDispatcher = function(){};
AbstractEventsDispatcher.prototype = {
callbacks: {},
bind: function(event_name, callback){
this.callbacks[event_name] = this.callbacks[event_name] || [];
this.callbacks[event_name].push(callback);
return this;// chainable
},
trigger: function(event_name, data){
this.dispatch(event_name, data);
return this;
},
dispatch: function(event_name, data){
var chain = this.callbacks[event_name];
if(typeof chain == 'undefined') return; // no callbacks for this event
for(var i = 0; i < chain.length; i++){
chain[i]( data )
}
}
};
/* Periodically send out dummy events
--------------------------------------------*/
var PusherMock = function( interval ){
var self = this;
var nextInterval = function(){
return Math.round(Math.random() * interval * 2)
}
var nextTick = function(){
var event = PusherMock.events[Math.floor(Math.random() * PusherMock.events.length)];
self.trigger(event.event, event.data);
setTimeout(nextTick, nextInterval());
}
nextTick();
};
// Extend from AbstractEventsDispatcher 'bind' and 'trigger' methods
PusherMock.prototype = new AbstractEventsDispatcher;
/* Add some events
--------------------------------------------*/
PusherMock.events = [
{
'event': "commits:commit",
'data': {
"repository": "rr10-team-3",
"author":"author 1",
"committed":"The committed timestamp",
"message":"The commit message 1",
"commitHash":"SHA of the commit22"
}
},
{
'event': 'irc:message',
'data': {
'message': '1st irc message',
'user': 'max13'
}
}
// etc
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment