博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
一个简单的MVVM雏形
阅读量:7097 次
发布时间:2019-06-28

本文共 2308 字,大约阅读时间需要 7 分钟。

这是实现的MVVM,使用定时器轮询,只支持{

{}}与input.value的修改。

这只能算是一个玩具,真正的MVVM需要有更复杂的扫描机制,JS解析器,双向绑定链什么的。

  
JS Bin
<!DOCTYPE html> <html> <head> <script src="http://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script> <meta charset="utf-8"> <title>JS Bin</title> </head> <body> <div data-component="input"> <template> <input type="text" name="username" tb-model="username" value="" /> <span>{
{ username }}</span> </template> </div> <script> var DIRECTIVE_ATTR_MODEL = 'tb-model', regMustache = /\{\{\s*(\w+)\s*\}\}/g, slice = Array.prototype.slice; function boot() { var components = slice.call(document.querySelectorAll('[data-component]'), 0); components.forEach(function (el) { var component = el.getAttribute('data-component'); bootComponent(el, window[component + 'Controller']); }); } function bootComponent(el, controller) { var $scope = {}, elFrag = el.querySelector('template').content.cloneNode(true); traverse(elFrag, $scope); el.appendChild(elFrag); controller($scope); } function traverse(root, $scope) { for (var el = root.firstChild; el; el = el.nextSibling) { parseElement(el, $scope); if (el) { traverse(el, $scope); } } } function parseElement(el, $scope) { if (el.nodeType === 1) { // element if (el.hasAttribute(DIRECTIVE_ATTR_MODEL)) { var model = el.getAttribute(DIRECTIVE_ATTR_MODEL); el.removeAttribute(DIRECTIVE_ATTR_MODEL); el.addEventListener('input', function () { $scope[model] = this.value; }); } } else if (el.nodeType === 3) { // text node var text = el.textContent, tpl = [], lastIndex = 0, match = regMustache.exec(text); while (match) { tpl.push(text.substring(lastIndex, regMustache.lastIndex - match[0].length)); tpl.push({ type: 'var', content: match[1] }); lastIndex = regMustache.lastIndex; match = regMustache.exec(text); } watch($scope, function () { text = ''; tpl.forEach(function (item) { text += typeof item === 'string' ? item : $scope[item.content]; }); el.textContent = text; }); } } function watch($scope, cb) { var old = _.cloneDeep($scope), timer; timer = setInterval(function () { if (!_.isEqual($scope, old)) { cb($scope, old); old = _.cloneDeep($scope); } }, 50); } function inputController($scope) { $scope.username = 'spring'; } boot(); </script> </body> </html>

运行代码

转载地址:http://hyhql.baihongyu.com/

你可能感兴趣的文章
Promise & Deferred objects in JavaScript Pt.1: Theory and Semantics.
查看>>
Joyoi花店橱窗(原tyvj1124)
查看>>
JavaMail基础案例开发
查看>>
被称"硬盘杀手"的几个win7系统服务如何关闭(转)
查看>>
C# 存储过程
查看>>
软件体系结构的第二次实验
查看>>
无聊记记
查看>>
ODI Scenario 场景
查看>>
操作JSON对象
查看>>
iOS 模态视图,视图之间的切换
查看>>
iptables
查看>>
.NET自动识别GB2312与UTF-8编码的文件
查看>>
Linux下apache日志分析与状态查看方法
查看>>
hdu2412(树形dp)
查看>>
js返回函数, 函数名后带多个括号的用法及join()的注意事项
查看>>
【NOIP2007】矩阵取数
查看>>
关于VIM在Win10下的无意义折腾
查看>>
ibatis example Class 使用
查看>>
android的触摸事件(转)
查看>>
springMVC与struts2的区别
查看>>