<body>
<div id="app">
<h1>{{message}}</h1>
</div>
</body>
var model = {
message: '网易云课堂',
data: [{}, {}, {}]
} //数据来自ajax请求返回的
Object.defineProperty(model, 'message', {
// value: 'second',
// configuration: false,
enumerable: false, //设置为false,不可遍历,一般场景是当让某个属性作为私有属性时,
}) //定义一个对象的某个属性的对象描述,
mvvm('app', model); //双向数据绑定之后
function mvvm(context, model) {
dom = document.getElementById(context);
(function(model, prop, value) {
//model->view 数据到视图
Object.defineProperty(model, prop, {
// value: '网易云课堂',
configuration: false,
enumerable: false,
// writable: true,
get: function() {
return value;
},
set: function(nValue) {
if (value !== nValue) {
value = nValue;
dom.children[0].innerText = value;
}
console.log(model);
}
});
//view -> model 视图到数据
var text = dom.children[0].innerText; //拿到视图的数据
Object.defineProperty(dom.children[0], 'innerText', {
// value: '网易云课堂',
configuration: false,
enumerable: false,
// writable: true,
get: function() {
return value;
},
set: function(nValue) {
if (text !== nValue) {
text = nValue;
model.message = text;
}
}
});
model.message = model.message;
})(model, 'message', model.message);
}
window.setTimeout(function() {
model.message = 'change1';
}, 5000)