Skip to content

Commit

Permalink
added onAndGet method
Browse files Browse the repository at this point in the history
  • Loading branch information
arvitaly committed Apr 7, 2018
1 parent 0074f95 commit a753e9d
Show file tree
Hide file tree
Showing 6 changed files with 840 additions and 296 deletions.
12 changes: 12 additions & 0 deletions __tests__/index-spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,16 @@ describe("Onemitter spec", () => {
const o1 = __1.default({ value: "test" });
expect(o1.get()).toBe("test");
});
it("onAndGet should call immediately if value existing", () => {
const o1 = __1.default({ value: "test" });
const cb = jest.fn();
o1.onAndGet(cb);
expect(cb.mock.calls).toEqual([["test"]]);
});
it("onAndGet should not call immediately if value not existing", () => {
const o1 = __1.default();
const cb = jest.fn();
o1.onAndGet(cb);
expect(cb.mock.calls.length).toBe(0);
});
});
13 changes: 13 additions & 0 deletions __tests__/index-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,17 @@ describe("Onemitter spec", () => {
const o1 = onemitter({ value: "test" });
expect(o1.get()).toBe("test");
});

it("onAndGet should call immediately if value existing", () => {
const o1 = onemitter({ value: "test" });
const cb = jest.fn();
o1.onAndGet(cb);
expect(cb.mock.calls).toEqual([["test"]]);
});
it("onAndGet should not call immediately if value not existing", () => {
const o1 = onemitter();
const cb = jest.fn();
o1.onAndGet(cb);
expect(cb.mock.calls.length).toBe(0);
});
});
6 changes: 6 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ class Onemitter {
on(cb) {
this.listeners.push(cb);
}
onAndGet(cb) {
this.listeners.push(cb);
if ("value" in this.store) {
cb(this.store.value);
}
}
off(cb) {
this.listeners = this.listeners.filter((c) => c !== cb);
}
Expand Down
6 changes: 6 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ export class Onemitter<T> {
public on(cb: (value: T) => any) {
this.listeners.push(cb);
}
public onAndGet(cb: (value: T) => any) {
this.listeners.push(cb);
if ("value" in this.store) {
cb(this.store.value as any);
}
}
public off(cb: (value: T) => any) {
this.listeners = this.listeners.filter((c) => c !== cb);
}
Expand Down
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,11 @@
},
"homepage": "https://github.com/arvitaly/onemitter#readme",
"devDependencies": {
"@types/jest": "^22.1.4",
"@types/jest": "^22.2.2",
"coveralls": "^3.0.0",
"jest": "^22.4.2",
"jest": "^22.4.3",
"tslint": "^5.9.1",
"typescript": "^2.7.2"
"typescript": "^2.8.1"
},
"jest": {}
}

0 comments on commit a753e9d

Please sign in to comment.