index.js:
var God = {
version:'1.0',
extends(name, obj){
// 调用初始化函数
this.init();
/*
* 我们约定对象中必须有 data和methdos2个属性
* 并且data是函数,methods是对象
* */
if('data' in obj && 'methods' in obj && typeof obj.data=='function' && typeof obj.methods=='object'){
var getData = obj.data();
if (typeof getData == 'object'){
Object.assign(obj.methods, getData, this);
this[name] = obj;
}
}
},
init(){
// 批量设置方法
Object.defineProperties(this,{
'init':{enumerable:false}, // 设置属性不可枚举
'extends':{enumerable:false}, // 设置属性不可枚举
});
var keys = Object.keys(this); // 列举出this当前是所有属性
this.$global = {}; // 创建一个新对象 叫做 $global
keys.forEach((key)=>{
this.$global[key] = this[key];
});
//Object.freeze(this.$global); // 冻结对象
this.watch('version',this.$global); // 监听这个属性
},
// 属性监控方法
watch(keyName,obj){
var _key = '_' + keyName;
if (!(_key in obj)) {
obj[_key] = obj[keyName]; //这是私有变量初始化值设置
}
Object.defineProperty(obj, keyName, {
set:value=>{
obj[_key] = value;
this.render(); //重新渲染html
},
get(){
return obj[_key];
}
});
},
// 渲染方法
render(){
document.getElementById('test').innerHTML = '当前版本是:' + this.$global.version;
}
};
var news = {
data(){
return {id:101, title:'新闻标题'};
},
methods:{
show(){
//this.$global.version = '2.0';
//alert(this.$global.version);
}
}
};
// 然后我们可以这样访问
God.extends('name',news);
//God.name.methods.show();
重点观察God
中的watch
方法,该方法实现了对属性的监控。在init
方法中调用了watch
方法来监听version
属性。
render
方法是一个渲染html页面的方法,在模板中God.render()
这样调用。
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="index.js"></script>
<script>
function changeVersion() {
God.$global.version = '2.0';
}
</script>
</head>
<body>
<div id="test"></div>
<button onclick="changeVersion()">更新版本</button>
<script>
// 调用渲染方法
God.render();
</script>
</body>
</html>
在模板index.html中,点击按钮后修改了version
的值,我们知道在watch
方法中观察属性的setter的之后,我们重新调用了render
来渲染页面。所以,我们应该可以实现html页面数据自动刷新。