Skip to content

Commit

Permalink
feat: add observable source from property changes
Browse files Browse the repository at this point in the history
Closes #1
  • Loading branch information
alexlafroscia committed Jan 29, 2019
1 parent 678432e commit 6b66b92
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 0 deletions.
5 changes: 5 additions & 0 deletions addon/index.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,7 @@
export { default as Route } from "./route";

export { default as subscribe } from "./decorators/subscribe";

export {
default as fromPropertyChange
} from "./observables/from-property-change";
16 changes: 16 additions & 0 deletions addon/observables/from-property-change.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { fromEventPattern } from "rxjs";
import { get } from "@ember/object";

export default function fromPropertyChange(subject, property) {
return fromEventPattern(
handler => {
subject.addObserver(property, subject, handler);
},
handler => {
subject.removeObserver(property, subject, handler);
},
(instance, prop) => {
return get(instance, prop);
}
);
}
48 changes: 48 additions & 0 deletions tests/unit/observables/from-property-change-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { module, test } from "qunit";
import { setupScheduler } from "ember-observable/test-support";
import td from "testdouble";
import EmberObject from "@ember/object";
import { fromPropertyChange } from "ember-observable";

class Dummy extends EmberObject {
foo = "foo";
}

module("Unit | Observables | fromPropertyChange", function(hooks) {
setupScheduler(hooks);

test("it emits events when a property changes", function(assert) {
const instance = Dummy.create();

const observer = td.function();
fromPropertyChange(instance, "foo").subscribe(observer);

instance.set("foo", "bar");
instance.set("foo", "bax");

assert.verify(observer("bar"), "Called for the first change");
assert.verify(observer("bax"), "Called for the second change");
});

test("no longer emits events for changes after unsubscribe", function(assert) {
const instance = Dummy.create();

const observer = td.function();
const subscription = fromPropertyChange(instance, "foo").subscribe(
observer
);

instance.set("foo", "bar");

subscription.unsubscribe();

instance.set("foo", "bax");

assert.verify(observer("bar"), "Called for the first change");
assert.verify(
observer("bax"),
{ times: 0 },
"Not called for the second change"
);
});
});

0 comments on commit 6b66b92

Please sign in to comment.