Skip to content

Instantly share code, notes, and snippets.

@ympbyc
Created May 10, 2012 15:18
Show Gist options
  • Select an option

  • Save ympbyc/2653852 to your computer and use it in GitHub Desktop.

Select an option

Save ympbyc/2653852 to your computer and use it in GitHub Desktop.
よく使うものだけまとめる
function Ym (obj) {
// Ym() returns an instance of this Constructor
var Constructor = function (obj) {
if (obj)
for (key in obj)
if (obj.hasOwnProperty(key))
this[key] = obj[key]
}
// Copy the prototype of the object given to our Ym object's prototype
// javascript 1.8.2 or lator
if (obj) Constructor.prototype = Object.getPrototypeOf(obj);
// Keep the event listener maps
var listenerStack = []; //for event emitter
// You know what it does
Constructor.prototype.each = function (fn) {
for (key in this)
if (this.hasOwnProperty(key))
fn(this[key], key);
return this;
},
// Register an event listener
Constructor.prototype.on = function (ev, listener) {
listenerStack.push({name : ev, listener : listener});
return this;
},
// Unset an event listener
Constructor.prototype.off = function (ev, listener) {
Ym(listenerStack).each(function (item, key) {
if (item && item.name === ev && item.listener === listener) listenerStack[key] = undefined;
});
return this;
},
// Emit listeners that are listening for this event
Constructor.prototype.fire = function (ev, obj) {
obj = obj || {};
Ym(listenerStack).each(function (item) {
if (item && item.name == ev) item.listener(obj);
});
return this;
},
// The first argument passed will extend an instance of Ym
// The second argument passed will extend the prototype of Ym
// *There should be a better notation
Constructor.prototype.extend = function (my, proto) {
var self = this;
Ym(my).each(function (item, key) {
self[key] = item;
});
Ym(proto).each(function (item, key) {
Constructor.prototype[key] = item;
});
return this;
}
return new Constructor(obj);
}
[
(function () {
var a = 0;
Ym().on('ev', function (e) {a = e}).fire('ev', 1);
return a;
})() === 1,
(function () {
var a = 0, f;
Ym().on('ev', f = function (e) {a = e}).off('ev', f).fire('ev', 1);
return a;
})() === 0,
Ym({a:1}).extend({b:2},{addAB : function () {return this.a + this.b}}).addAB() === 3
]
@ympbyc

ympbyc commented May 12, 2012

Copy link
Copy Markdown
Author

mapやkeysはべつにあとからextendすればいいやと思って消しました

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment