Skip to content

Instantly share code, notes, and snippets.

@huzidaha
Created June 10, 2017 08:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huzidaha/e35a181246f85dacbed1dae0ab39c505 to your computer and use it in GitHub Desktop.
Save huzidaha/e35a181246f85dacbed1dae0ab39c505 to your computer and use it in GitHub Desktop.
ScriptOJ MVVM(勉强符合题意版本,可以优化地方很多)
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