Created
March 21, 2017 03:38
-
-
Save googya/38d3de7c4fdc395dca76216403027f15 to your computer and use it in GitHub Desktop.
使用 setter/getter 实现 observable
This file contains hidden or 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
| function Seer(dataObj) { | |
| let signals = {}; | |
| observeData(dataObj); | |
| return { | |
| data: dataObj, | |
| observe, | |
| notify | |
| } | |
| function observe(property, signalHandler) { | |
| if (!signals[property]) signals[property] = [] | |
| signals[property].push(signalHandler) | |
| } | |
| function notify(signal) { | |
| if (!signals[signal] || signals[signal].length < 1) return; | |
| signals[signal].forEach((signalHander) => signalHander()); | |
| } | |
| function makeReactive(obj, key) { | |
| let val = obj[key] | |
| Object.defineProperty(obj, key, { | |
| get() { | |
| return val; | |
| }, | |
| set(newVal) { | |
| val = newVal; | |
| notify(key); | |
| } | |
| }) | |
| } | |
| function observeData(obj) { | |
| for (let key in obj) { | |
| if (obj.hasOwnProperty(key)) { | |
| makeReactive(obj, key) | |
| } | |
| } | |
| } | |
| } | |
| const App = new Seer({ | |
| title: 'Game of Thrones', | |
| firstName: 'Jon', | |
| lastName: 'Snow', | |
| age: 25 | |
| }) | |
| App.observe('firstName', () => console.log(App.data.firstName)) | |
| App.observe('lastName', () => console.log(App.data.lastName)) | |
| App.data.firstName = 'Sansa' | |
| App.data.lastName = 'Stark' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment