Skip to content

Instantly share code, notes, and snippets.

@andiwand
Last active November 5, 2019 06:20
Show Gist options
  • Save andiwand/639c01855c357339c5b382727d6239da to your computer and use it in GitHub Desktop.
Save andiwand/639c01855c357339c5b382727d6239da to your computer and use it in GitHub Desktop.
Javascript observable objects with Proxy (ECMA-262 6th Edition, https://mzl.la/203LEg9)
ObservableArray = function(array) {
if (array == null) array = [];
if (!Array.isArray(array)) throw new TypeError('argument is not an array');
var listeners = [];
this.toString = array.toString;
this.listen = function(listener) {
listeners.push(listener);
};
this.unlisten = function(listener) {
var index = listeners.indexOf(listener);
if (index >= 0) listeners.splice(index, 1);
};
var fire = function(index, removed, addedCount) {
listeners.forEach(function(listener) {
listener(index, removed, addedCount);
});
};
var proxies = {
push: function() {
Array.prototype.push.apply(array, arguments);
fire(array.length - arguments.length, [], arguments.length);
},
pop: function() {
var removed = [array[-1]];
Array.prototype.pop.apply(array);
fire(array.length, removed, 0);
},
shift: function() {
var removed = [array[0]];
Array.prototype.shift.apply(array);
fire(0, removed, 0);
},
unshift: function() {
Array.prototype.unshift.apply(array, arguments);
fire(0, [], arguments.length);
},
splice: function(index, removeCount) {
var removed = array.slice(index, index + removeCount);
Array.prototype.splice.apply(array, arguments);
fire(index, removed, arguments.length - 2);
}
};
var handler = {
get: function(target, property) {
if (property in proxies) return proxies[property];
return target[property];
},
set: function(target, property, value) {
var removed = [target[property]];
target[property] = value;
fire(property, removed, 1);
return true;
}
};
Object.setPrototypeOf(this, new Proxy(array, handler));
};
@andiwand
Copy link
Author

andiwand commented Oct 5, 2016

Thanks!

  1. Never!
  2. It would be better to use if (array === undefined) I guess.
  3. True
  4. True

Further, I should avoid setPrototypeOf. Maybe just return the Proxy and add the listener functions there.

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