Skip to content

Instantly share code, notes, and snippets.

@kpnemo
Created October 3, 2015 13:30
Show Gist options
  • Select an option

  • Save kpnemo/0d1071f8eba0d3217786 to your computer and use it in GitHub Desktop.

Select an option

Save kpnemo/0d1071f8eba0d3217786 to your computer and use it in GitHub Desktop.
var Events = function(){};
Events.prototype.on = function(eventName, callback){
if(!this.events) this.events = {};
try{
if(this.events[eventName] && this.events[eventName].length > 0){
this.events[eventName].push(callback);
} else {
this.events[eventName] = [callback];
}
} catch(ex){
console.error(ex);
}
}
Events.prototype.off = function(eventName){
if(!this.events) this.events = {};
if(eventName){
if(this.events[eventName]) delete this.events[eventName];
} else {
delete this.events;
this.events = {};
}
}
Events.prototype.trigger = function(){
if(!this.events) this.events = {};
var _eventName = arguments[0] || null,
_vars = [];
if(_eventName == null){
console.error('No event name provided');
return;
}
if(arguments.length > 1){
for(var i=0; i<= arguments.length-1; i++){
_vars.push(arguments[i+1]);
}
}
if(this.events[_eventName] && this.events[_eventName].length > 0){;
for(var l=0;l<=this.events[_eventName].length -1; l++){
this.events[_eventName][l](_vars);
}
}
}
/**
* ==============================
*/
var worker1 = function(){
console.log('Worker 1');
var self = this;
var _result = [1,2, 3];
this.run = function(){
console.log('Run');
setTimeout(function(){
console.log('Running');
//console.log(self, 'self');
self.trigger('ready', _result);
}, 1000)
}
return this;
}
worker1.prototype = Events.prototype;
var worker2 = function(){
console.log('Worker 2');
var self = this;
var _result = [1,2, 3];
this.run = function(){
console.log('Run');
setTimeout(function(){
console.log('Running');
//console.log(self, 'self');
self.trigger('ready', _result);
}, 5000)
return this;
}
return this;
}
worker2.prototype = Events.prototype;
var exe = function(){
var wrk1 = new worker1();
var wrk2 = new worker2();
wrk1.on('ready', function(result){
console.log('Worker 1 ready', result);
})
wrk1.run();
wrk2.on('ready', function(result){
console.log('Worker 2 ready', result);
})
wrk2.run();
}
$(window).on('load', function(){
var v = function(){
this.a = 1;
};
//z.prototype = Backbone.Events;
_.extend(v.prototype, Backbone.Events);
var z = new v();
z.a = 3;
console.log(z.a, '===');
z.on('a', function(){
console.log('bla');
})
z.trigger('a');
console.log(z);
})
exe();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment