Created
August 2, 2014 03:50
-
-
Save mmckegg/44c31fa6c51ed15b06ad to your computer and use it in GitHub Desktop.
observable array
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
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