-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathrevue.js
75 lines (74 loc) · 2.2 KB
/
revue.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import {
set as setProp,
get as getProp
} from 'object-path'
import shallowEqual from './utils/shallowEqual'
export default function(Vue, {
store = null,
actions = null
} = {}) {
if (process.env.NODE_ENV !== 'production' && typeof store !== 'object') {
throw new TypeError('[Revue] Expected store to be an object')
}
const re = /^([a-zA-Z0-9\._-]+)\s{1,2}as\s{1,2}([a-zA-Z0-9\._-]+)$/i
// bring redux to revue
if (actions) {
Object.defineProperty(Vue.prototype, '$actions', {
value: actions
})
}
Object.defineProperties(Vue.prototype, {
'$store': {
value: {
get state() {
return store.getState()
},
dispatch: store.dispatch
}
},
'$subscribe': {
value(...args) {
if (this._calledOnce) {
if (process.env.NODE_ENV === 'production') {
return false
}
throw new Error('[Revue] You can only subscribe once, pass multi args to subscribe more than one state.')
}
this._calledOnce = true
this._unsubscribers = []
args.forEach(prop => {
// realProp: property name/path in your instance
// storeProp: property name/path in Redux store
let realProp = prop,
storeProp = prop
if (re.test(prop)) {
[, storeProp, realProp] = prop.match(re)
}
let currentValue = getProp(store.getState(), storeProp)
const handleChange = () => {
let previousValue = currentValue
currentValue = getProp(store.getState(), storeProp)
if (!shallowEqual(previousValue, currentValue)) {
setProp(this._data, realProp, currentValue)
}
}
this._unsubscribers.push(store.subscribe(handleChange))
})
}
},
'$unsubscribe': {
value() {
if (this._unsubscribers && this._unsubscribers.length > 0) {
this._calledOnce = false
this._unsubscribers.forEach(un => un())
}
}
}
})
// global mixin
Vue.mixin({
beforeDestroy() {
this.$unsubscribe()
}
})
}