Skip to content

Instantly share code, notes, and snippets.

@geoffb
Created November 6, 2010 03:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geoffb/665176 to your computer and use it in GitHub Desktop.
Save geoffb/665176 to your computer and use it in GitHub Desktop.
Fucking around
(function () {
// Extends the base Object with data getter/setter and event target
var proto = Object.prototype;
proto._data = {};
proto._listeners = {};
proto.set = function (key, value) {
var old = this.get(key);
this._data[key] = value;
this.dispatchEvent({
type: "data_updated"
});
};
proto.setBatch = function (data) {
for (var key in data) {
this._data[key] = data[key];
}
this.dispatchEvent({
type: "data_updated"
});
};
proto.get = function (key) {
return this._data[key];
};
proto.getAll = function () {
return this._data;
};
proto.addEventListener = function (type, fn) {
if (!this._listeners[type]) {
this._listeners[type] = [];
}
this._listeners[type].push(fn);
};
proto.dispatchEvent = function (e) {
e.target = this;
if (this._listeners[e.type]) {
this._listeners[e.type].forEach(function (listener, key) {
listener(e);
});
}
};
proto.save = function () {
return JSON.stringify(this._data);
};
proto.load = function (json) {
var data = JSON.parse(json);
this.setBatch(data);
this.dispatchEvent({
type: "data_loaded"
});
};
}());
var Vector2 = function (x, y) {
this.setBatch({
x: x,
y: y
});
};
var v = new Vector2(2, 3);
console.log(v.get("y"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment