Skip to content

Commit

Permalink
spiked out a basic implementation of ObjectWrapper#watch (see #49)
Browse files Browse the repository at this point in the history
  • Loading branch information
dtao committed Dec 10, 2013
1 parent 235dcee commit d789f5c
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 0 deletions.
33 changes: 33 additions & 0 deletions lazy.js
Original file line number Diff line number Diff line change
Expand Up @@ -4369,6 +4369,39 @@
return clearTimeout;
}

/**
* Watches for all changes to a specified property of an object.
*/
ObjectWrapper.prototype.watch = function(propertyName) {
return new WatchedPropertySequence(this.source, propertyName);
};

function WatchedPropertySequence(object, propertyName) {
this.listeners = [];

var listeners = this.listeners,
index = 0;

Object.defineProperty(object, propertyName, {
get: function() {
return object[propertyName];
},

set: function(value) {
Lazy(listeners).each(function(listener) {
listener(value, index);
});
++index;
}
});
}

WatchedPropertySequence.prototype = new AsyncSequence();

WatchedPropertySequence.prototype.each = function(fn) {
this.listeners.push(fn);
};

/**
* A StreamLikeSequence comprises a sequence of 'chunks' of data, which are
* typically multiline strings.
Expand Down
1 change: 1 addition & 0 deletions spec/node_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ require("./find_spec.js");
require("./min_spec.js");
require("./max_spec.js");
require("./sum_spec.js");
require("./watch_spec.js");

// Sequence types
require("./string_like_sequence_spec.js");
Expand Down
45 changes: 45 additions & 0 deletions spec/watch_spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
describe("Lazy", function() {
describe("watch", function() {
it("watches an object for changes to the specified property", function() {
var object = {},
callback = jasmine.createSpy();

Lazy(object).watch('foo').each(callback);

object.foo = 1;
object.foo = 'bar';
object.foo = null;

expect(callback.callCount).toBe(3);
expect(callback.calls[0].args).toEqual([1, 0]);
expect(callback.calls[1].args).toEqual(['bar', 1]);
expect(callback.calls[2].args).toEqual([null, 2]);
});

it("provides access to map, filter, etc.", function() {
function upcase(str) {
return str.toUpperCase();
}

function blank(str) {
return str.length === 0;
}

var object = {},
callback = jasmine.createSpy();

Lazy(object).watch('foo').compact().map(upcase).each(callback);

object.foo = '';
object.foo = 'bar';
object.foo = null;

expect(callback.callCount).toBe(1);

// Given the implementation, I don't think there's a great way around
// this? (Having to pass the index of the assignment rather than the
// "adjusted" index.)
expect(callback.calls[0].args).toEqual(['BAR', 1]);
});
});
});

0 comments on commit d789f5c

Please sign in to comment.