脏值检查
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>two-way binding</title>
</head>
<body onload="init()">
<button ng-click="inc">
Increase
</button>
<button ng-click="reset">
Reset
</button>
<span style="color:red" ng-bind="counter"></span>
<span style="color:blue" ng-bind="counter"></span>
<span style="color:green" ng-bind="counter"></span>
<script type="text/javascript">
/* 数据模型区开始 */
var counter = 0;
function inc() {
counter++;
}
function reset() {
counter = 0;
}
/* 数据模型区结束 */
/* 绑定关系区开始 */
function init() {
bind();
}
function bind() {
var list = document.querySelectorAll("[ng-click]");
for (var i=0; i<list.length; i++) {
list[i].onclick = (function(index) {
return function() {
window[list[index].getAttribute("ng-click")]();
apply();
};
})(i);
}
}
function apply() {
var list = document.querySelectorAll("[ng-bind='counter']");
for (var i=0; i<list.length; i++) {
if (list[i].innerHTML != counter) {
list[i].innerHTML = counter;
}
}
}
/* 绑定关系区结束 */
</script>
</body>
</html>
es5 的 getter 和 setter
var a = { zhihu:0 };
Object.defineProperty(a, 'zhihu', {
get: function() {
console.log('get:' + zhihu);
return zhihu;
},
set: function(value) {
zhihu = value;
console.log('set:' + zhihu);
}
});
a.zhihu = 2; // set:2
console.log(a.zhihu); // get:2
es6 的 Proxy
let a = new Proxy({}, {
set: function(obj, prop, value) {
obj[prop] = value;
if (prop === 'zhihu') {
console.log("set " + prop + ": " + obj[prop]);
}
return true;
}
});
a.zhihu = 100;
参考资料:
网友评论