Skip to content

Instantly share code, notes, and snippets.

@ushiboy
Created November 16, 2013 13:34
Show Gist options
  • Save ushiboy/7500227 to your computer and use it in GitHub Desktop.
Save ushiboy/7500227 to your computer and use it in GitHub Desktop.
ObjectのなんちゃってObservableみたいな。
function Observable(o) {
o._$eObj = $({});
var key,
fn;
for (key in o) {
fn = o[key];
if (typeof(fn) === 'function') {
o[key] = (function(_fn) {
return function() {
var ret = _fn.apply(o, arguments);
o._$eObj.trigger('update', o);
return ret;
};
})(fn);
}
}
o.observe = function(listener) {
o._$eObj.on('update', listener);
};
return o;
}
var user = Observable({
setName : function(name) {
this.name = name;
}
});
user.observe(function(evt, o) {
console.log(o.name);
});
user.setName('test');
console.log(user.name);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment