Last active
November 5, 2019 06:20
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!
Further, I should avoid setPrototypeOf. Maybe just return the Proxy and add the listener functions there.