Created
June 10, 2017 08:48
-
-
Save huzidaha/e35a181246f85dacbed1dae0ab39c505 to your computer and use it in GitHub Desktop.
ScriptOJ MVVM(勉强符合题意版本,可以优化地方很多)
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
const bindViewToData = (el, data) => { | |
Object.keys(data).forEach((k) => { | |
let v = data[k] | |
Object.defineProperty(data, k, { | |
get () { | |
return v | |
}, | |
set (nv) { | |
v = nv | |
applyChanges() | |
} | |
}) | |
}) | |
let changes = [] | |
const parse = (el) => { | |
Array.from(el.childNodes).forEach((c) => { | |
if(!(c instanceof Text)) parse(c) | |
else { | |
changes.push(((originExp) => () => { | |
insertExpForTextNode(c, originExp) | |
})(c.nodeValue)) | |
} | |
}) | |
} | |
const insertExpForTextNode = (node, originExp) => { | |
const newValue = originExp.replace(/{{[\s\S]+?}}/g, function (exp) { | |
exp = exp.replace(/[{}]/g, '') | |
return execute(exp) | |
}) | |
if (newValue !== node.nodeValue) node.nodeValue = newValue | |
} | |
const execute = (exp) => { | |
return new Function(...Object.keys(data), `return ${exp}`)(...Object.values(data)) | |
} | |
const applyChanges = () => { | |
setTimeout(() => { | |
changes.forEach((f) => f()) | |
}) | |
} | |
parse(el) | |
applyChanges() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment