Skip to content

Commit f3388c5

Browse files
committed
feat:add two new methods onStates/offStates
1 parent 8f74427 commit f3388c5

File tree

2 files changed

+34
-3
lines changed

2 files changed

+34
-3
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "hy-event-store",
3-
"version": "1.1.1",
3+
"version": "1.2.0",
44
"description": "An event-based global state management tool for vue, react, mini-program, ect.",
55
"main": "src/index.js",
66
"scripts": {

src/event-store.js

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ class HYEventStore {
1818
this.state = options.state
1919
this._observe(options.state)
2020
this.event = new EventBus()
21+
this.eventV2 = new EventBus()
2122
}
2223

2324
_observe(state) {
@@ -32,6 +33,7 @@ class HYEventStore {
3233
if (_value === newValue) return
3334
_value = newValue
3435
_this.event.emit(key, _value)
36+
_this.eventV2.emit(key, { [key]: _value })
3537
}
3638
})
3739
})
@@ -40,9 +42,8 @@ class HYEventStore {
4042
onState(stateKey, stateCallback) {
4143
const keys = Object.keys(this.state)
4244
if (keys.indexOf(stateKey) === -1) {
43-
throw new Error("then state does not contain your key")
45+
throw new Error("the state does not contain your key")
4446
}
45-
4647
this.event.on(stateKey, stateCallback)
4748

4849
// callback
@@ -53,7 +54,37 @@ class HYEventStore {
5354
stateCallback.apply(this.state, [value])
5455
}
5556

57+
// ["name", "age"] callback1
58+
// ["name", "height"] callback2
59+
60+
onStates(statekeys, stateCallback) {
61+
const keys = Object.keys(this.state)
62+
const value = {}
63+
for (const theKey of statekeys) {
64+
if (keys.indexOf(theKey) === -1) {
65+
throw new Error("the state does not contain your key")
66+
}
67+
this.eventV2.on(theKey, stateCallback)
68+
value[theKey] = this.state[theKey]
69+
}
70+
71+
stateCallback.apply(this.state, [value])
72+
}
73+
74+
offStates(stateKeys, stateCallback) {
75+
stateKeys.forEach(theKey => {
76+
if (keys.indexOf(stateKey) === -1) {
77+
throw new Error("the state does not contain your key")
78+
}
79+
this.eventV2.off(theKey, stateCallback)
80+
})
81+
}
82+
5683
offState(stateKey, stateCallback) {
84+
const keys = Object.keys(this.state)
85+
if (keys.indexOf(stateKey) === -1) {
86+
throw new Error("the state does not contain your key")
87+
}
5788
this.event.off(stateKey, stateCallback)
5889
}
5990

0 commit comments

Comments
 (0)