Observable arrays with live data binding, callbacks for data transformation, and callbacks for any modification
npm install live-arraysProxy, a new JavaScript language feature. It will work in FireFox by default, Chrome with the "Experimental JavaScript" about:flag enabled, and Node.js 0.8+ when run with this flag __node --harmony__.npm install live-arrays
javascript
// node
var BoundArray = require('live-arrays').BoundArray,
ArrayView = require('live-arrays').ArrayView,
subarray = require('live-arrays').subarray;
//browser
`API
#### subarray
__subarray(input, start, end)__
Works the same as array buffer subarray, except for any indexed object. This will be a live view of the underlying input array. It will inherit from the same prototype and look mostly the same. It will have its own properties aside from the indexed ones. And is a separate object, but its indexed properties will read and write to the given input.
#### BoundArray
__BoundArray(onchange, onresize)__
Functions as a normal array but with callbacks when changed and optionally when resized.
onchange and onresize can set during construction and are also properties on the array that can be changed.
`javascript
var list = document.body.appendChild(document.createElement('ul'));var bound = new BoundArray;
bound.onchange = function(index, value, oldValue){
list.children[index].textContent = value;
};
bound.onresize = function(size, oldSize){
if (size > oldSize) {
for (var i = oldSize; i < size; i++)
list.appendChild(document.createElement('li'));
} else {
for (var i = oldSize; i > size; i--)
list.removeChild(list.children[i - 1]);
}
};
`#### ArrayView
__ArrayView__(inputArray, transformer, untransformer)__
Take an existing indexed object and create a transformed view of it. The ArrayView will have the same length but items are run through your transform call back before being returned. This a live view of the input array. Whenever a property is accessed it will be based on whatever is in the first array at the time. Length changes will be reflected as well.
The optional untransformer changes the array from readonly to changeable. Whenever a modification is done to your ArrayView, you must translate it back to the value that should go into the original array.
`javascript
var list = document.body.appendChild(document.createElement('ul'));var view = new ArrayView({
input: list.children,
transformer: function(item, index){
return item.textContent;
},
untransformer: function(value, index){
if (index >= list.children.length) {
for (var i = list.children.length; i <= index; i++)
list.appendChild(document.createElement('li'));
} else if (value === undefined)
list.removeChild(list.children[index]);
return list.children[index].textContent = value;
}
});
view.push.apply(view, Object.keys(window));
``