Skip to content

Instantly share code, notes, and snippets.

@oti
Last active January 23, 2016 08:02
Show Gist options
  • Save oti/f366234d626de52e3bdd to your computer and use it in GitHub Desktop.
Save oti/f366234d626de52e3bdd to your computer and use it in GitHub Desktop.
EventEmitter
(function(w, jQ){
var window = w;
var $ = jQ;
var resizeConfig = {
bindSeletor: window,
name: 'resize',
throttle: true,
threshold: 600,
observabled: [
function(param){
console.log(param);
}
],
emitParams: function() {
return $(window).width();
}
};
/*
* イベントの検出と通知
*/
var EventEmitter = (function(data){
function EventEmitter(data) {
this.bindSeletor = data.bindSeletor;
this.name = data.name;
this.throttle = data.throttle;
this.threshold = data.threshold;
this.observabled = data.observabled;
this.emitParams = data.emitParams;
this.timer = null;
}
EventEmitter.prototype.init = function() {
var self = this;
self.attachEvents();
};
EventEmitter.prototype.attachEvents = function() {
var self = this;
$(self.bindSeletor).on(self.name, self.catchEvents.bind(self));
};
EventEmitter.prototype.catchEvents = function() {
var self = this;
if (self.throttle) {
clearTimeout(self.timer);
self.timer = setTimeout(function() {
self.emitEvents();
}, self.threshold);
} else {
self.emitEvents();
}
};
EventEmitter.prototype.emitEvents = function() {
var self = this;
var params = self.emitParams();
var obs = self.observabled;
var obsLength = obs.length;
if(obsLength) {
for (var i=0;i<obsLength;i++) {
// 登録された関数を実行
obs[i](params);
}
}
};
return EventEmitter;
})();
// document ready
$(function(){
var resizeEmitter = new EventEmitter(resizeConfig);
resizeEmitter.init();
});
})(window, jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment