Skip to content

Instantly share code, notes, and snippets.

@jpiccari
Last active August 29, 2015 14:01
Show Gist options
  • Save jpiccari/e76cbff3a4f2a31c5a72 to your computer and use it in GitHub Desktop.
Save jpiccari/e76cbff3a4f2a31c5a72 to your computer and use it in GitHub Desktop.
AMD Observer module, depends on EventEmitter (see my other gists). (235 bytes minified, gzipped)
define(
'Observer',
[
'EventEmitter'
],
function(EventEmitter) {
'use strict';
function copyValue(value) {
if (typeof value === 'object') {
return value instanceof Array
? value.slice()
: Object.create(value);
}
return value;
}
return function(model) {
model = model || {};
return EventEmitter({
get: function(key) {
return copyValue(model[key]);
},
set: function(key, value) {
var change = {
type: 'updated',
object: this,
name: key,
oldValue: copyValue(model[key]),
value: copyValue(value)
};
model[key] = value;
this.trigger('change', change);
}
});
};
}
);
define("Observer",["EventEmitter"],function(c){function d(a){return"object"===typeof a?a instanceof Array?a.slice():Object.create(a):a}return function(a){a=a||{};return c({get:function(b){return d(a[b])},set:function(b,e){var c={type:"updated",object:this,name:b,oldValue:d(a[b]),value:d(e)};a[b]=e;this.trigger("change",c)}})}});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment