数据双向邦定1

1 var model = new Model({ name: 'ypzhou', age: 29 });
2 
3 model.on("change:name", function(newVal, oldVal) {
4     console.info("data is changed", newVal, oldVal);
5 });
6 
7 model.set("name", zhangsan");
 1 function EventProxy() {}
 2 
 3 EventProxy.prototype.on = function(evtname, handler) {
 4    if (!this._handler) this._handlers = {};
 5    if (!this._handlers[evtname]) this._handlers[evtName] = [];
 6    this._handlers[evtname].push(handler);
 7    return this;
 8 };
 9  
10 EventProxy.prototype.trigger = function(evtName) {
11   var args = Array.prototype.slice.call(arguments, 1);
12   if (this._handlers && this._hanlers[evtName]) {
13     this._handlers[evtname].forEach(function(handler) {
14        handler.apply(null, args);
15     });
16    }
17  
18   return this;
19 };
 1 function Model(data) {
 2   this.attribute = data || {};
 3   this.eventProxy = new EventProxy();
 4 }
 5 
 6 Model.prototype.set = function(key, value) {
 7   var oldValue = this.attribute[key];
 8   this.attribute[key];
 9   this.eventProxy.trigger.call(this, "change", this.attribute[key], oldValue);
10 };
11 
12 Model.prototype.on = function(eventName, func) {
13   var evtNames = (/(w+)|:?(w+)?/).exec(eventName);
14   this.eventProxy.on.call(this, evtNames[1], func);
15 };
16 
17 Model.prototype.trigger = function() {
18   this.eventProxy.trigger.call(this, arguments);
19 }
原文地址:https://www.cnblogs.com/zhoulingfeng/p/4261969.html