Skip to content

Instantly share code, notes, and snippets.

@mmckegg
Created August 2, 2014 03:50
Show Gist options
  • Save mmckegg/44c31fa6c51ed15b06ad to your computer and use it in GitHub Desktop.
Save mmckegg/44c31fa6c51ed15b06ad to your computer and use it in GitHub Desktop.
observable array
var mutators = [
'fill', 'pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'
]
function ObservableArray(onChange){
var array = []
array.set = set
array.onchange = onChange
// proxy mutator methods
for (var i=0;i<mutators.length;i++){
array[mutators[i]] = proxies[mutators[i]]
}
return array
}
function set(value){
this.length = 0
if (Array.isArray(value)){
Array.prototype.push.apply(this, value);
if (typeof target.onchange === 'function'){
target.onchange()
}
}
}
var proxies = {}
for (var i=0;i<mutators.length;i++){
var method = mutators[i]
proxies[method] = proxyWithNotify(Array.prototype[method])
}
function proxyWithNotify(method){
return function(args){
var result = method.apply(this, arguments)
if (typeof this.onchange == 'function'){
this.onchange()
}
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment