Created
April 25, 2018 16:06
-
-
Save kazu69/093272c1183f2cfcafa079428713394c to your computer and use it in GitHub Desktop.
Vue.js reactive object pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Vue.js like reactive object pattern | |
// show detail https://github.com/vuejs/vue/blob/master/src/core/observer/index.js | |
const Watcher = function() {} | |
Watcher.prototype.update = function () { | |
console.log('Watcher update') | |
} | |
const Dep = function(watcher) { | |
this.id = this.id ? this.id ++ : 0 | |
this.subs = [] | |
} | |
Dep.prototype.addSub = function (sub) { | |
this.subs.push(sub) | |
} | |
Dep.prototype.notify = function() { | |
const subs = this.subs.slice() | |
subs.map(sub => { | |
sub.update() | |
}) | |
} | |
const defineReactive = (obj, key, val, customSetter, shellow) => { | |
const dep = new Dep() | |
const watcher = new Watcher() | |
dep.addSub(watcher) | |
const property = Object.getOwnPropertyDescriptor(obj, key) | |
if (property && property.configurable === false) { | |
return | |
} | |
const getter = property && property.get | |
const setter = property && property.set | |
Object.defineProperty(obj, key, { | |
enumerable: true, | |
configurable: true, | |
get: function reactiveGetter () { | |
const value = getter ? getter.call(obj) : val | |
return value | |
}, | |
set: function reactiveSetter (newVal) { | |
const value = getter ? getter.call(obj) : val | |
/* eslint-disable no-self-compare */ | |
if (newVal === value || (newVal !== newVal && value !== value)) { | |
return | |
} | |
if (customSetter && typeof customSetter === 'function') { | |
customSetter() | |
} | |
if (setter) { | |
setter.call(obj, newVal) | |
} else { | |
val = newVal | |
} | |
dep.notify() | |
} | |
}) | |
} | |
const data = {} | |
const key = 'message' | |
const val = 'Hello' | |
console.log(data) // => {} | |
// define reactive property to object | |
defineReactive(data, key, val) | |
console.log(data) // => { message: [Getter/Setter] } | |
console.log(data.message) // => Hello | |
console.log(data.message = 'こんにちわ') // =>こんにちわ | |
console.log(data.message = '你好') // => 你好 | |
/* | |
node main.js | |
{} | |
{ message: [Getter/Setter] } | |
Hello | |
Watcher update | |
こんにちわ | |
Watcher update | |
你好 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment