Skip to content
This repository has been archived by the owner on Mar 13, 2018. It is now read-only.

Add array contents observer #83

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,35 @@ ArrayObserver also exposes a utility function: `applySplices`. The purpose of `a
AraryObserver.applySplices = function(previous, current, splices) { }
```

### ArrayContentsObserver

ArrayContentsObserver observes the state of the given array, as well as the elements of the array itself. To observe the elements, the constructor takes a function which, when passed an element of the array, returns a new observer object for observing that element.

```JavaScript
var arr = [{foo: 1, bar: 2}];
var observerFactory = function(elem) {
return new ObjectObserver(elem);
};
var observer = ArrayContentsObserver(arr, observerFactory);
observer.open(function(type, data) {
switch (type) {
case 'splices': {
// "data" is an array of splice arguments, as with ArrayObserver
break;
}

case 'elemChange': {
data.index; // The index of the array that the change occured at.
data.changeArgs; // The array of arguments that were passed to the
// element's observation function
}
}
});

arr[0].foo = 2; // Function called with ['elemChanged', [{}, {}, {foo: 2}]]
arr.push({foo: 3, bar: 4}); // Function called with ['splices', [{index: 1, removed: [], addedCount: 1}]]
```

### ObjectObserver

ObjectObserver observes the set of own-properties of an object and their values.
Expand Down
103 changes: 102 additions & 1 deletion src/observe.js
Original file line number Diff line number Diff line change
Expand Up @@ -973,6 +973,106 @@
});
};

function ArrayContentsObserver(array, observerConstructor) {
if (!Array.isArray(array)) {
throw new Error('Input object not an array: ' + input);
}
Observer.call(this, array);

this.elemObserverConstructor_ = observerConstructor;
this.elemObservers_ = null;
this.arrayObserver_ = null;
this.isSkippingChanges_ = false;
}

ArrayContentsObserver.prototype = {
__proto__: Observer.prototype,
connect_: function() {
this.elemObservers_ = [];

var self = this;

this.value_.forEach(function(elem) {
self.elemObservers_.push(self.startElemObserver_(elem));
});

this.arrayObserver_ = new ArrayObserver(this.value_);
this.arrayObserver_.open(function(splices) {
// Check to ensure that indexes are in increasing order
var currIndex = -1;
slices.forEach(function(splice) {
if (currIndex >= splice.index) {
throw new Error('Got bad ordering of splices');
}

currIndex = splice.index;

self.handleSplice_(splice);
});

if (!this.isSkippingChanges_) {
this.report_(['splice', slices]);
}
});
},

disconnect_: function() {
this.elemObservers_.forEach(function(obs) {
obs.close();
});

this.elemObservers_ = null;

this.arrayObserver_.close();
this.arrayObserver_ = null;
},

check_: function(changeRecords, skipChanges) {
// changeRecords should always be null/undefined, since we only depend
// on the observer API.
if (skipChanges) {
for (var i = 0; i < this.elemObservers_; i++) {
this.elemObservers_[i].discardChanges();
}
// Apply changes from the array, but don't report any messages.
this.isSkippingChanges_ = true;
this.arrayObserver_.dispatch();
this.isSkippingChanges_ = false;
}

return false;
},

startElemObserver_: function(elem) {
var observer = this.elemObserverConstructor_(elem);
var self = this;
observer.open(function() {
self.report_(['indexChange', {
index: self.elemObservers_.indexOf(observer),
changeArgs: arguments,
}]);
});
return observer;
},

handleSplice_: function(splice) {
// Close the entries that have been removed.
for (var i = splice.index; i < splice.index + splice.removed.length; i++) {
this.tokenObservers[i].close();
}

var addedObservers = [];

for (var i = splice.index; i < splice.index + splice.addedCount; i++) {
addedObservers.push(this.startElemObserver_(this.value_[i]));
}

Array.prototype.splice.apply(
this.tokenObservers,
[splice.index, splice.removed.length].concat(addedObservers));
},
}

function PathObserver(object, path) {
Observer.call(this);

Expand Down Expand Up @@ -1700,12 +1800,13 @@
expose.ArrayObserver.calculateSplices = function(current, previous) {
return arraySplice.calculateSplices(current, previous);
};
expose.ArrayContentsObserver = ArrayContentsObserver;

expose.ArraySplice = ArraySplice;
expose.ObjectObserver = ObjectObserver;
expose.PathObserver = PathObserver;
expose.CompoundObserver = CompoundObserver;
expose.Path = Path;
expose.ObserverTransform = ObserverTransform;

})(typeof global !== 'undefined' && global && typeof module !== 'undefined' && module ? global : this || window);