VUE 響應式原理- 續
阿新 • • 發佈:2019-01-01
VUE響應式原理,再來一個比較貼合實際的例子。假如我是房東, 我到房產中介去掛了一套房子要出售,那房產中介小哥就會把這個房子釋出出去,有一些購房者有意向的話,就會去房產中介小哥那裡去詢問價格,房產中介小哥就讓潛在購房者登記,並告訴潛在購房者如果房東價格鬆動會即使通知你。房東看房產大勢不好,國家要出臺限購限售政策,一咬牙一跺腳想降級出手,那麼他就會告訴中介降級20萬,房產中介小哥就會挨個打電話或微信告訴潛在購房者:“大哥,好訊息,房東降級20萬”。
var house = { price : "26000/square meter" }; // take advantage of Object's access property function defineReactive(obj, key, val) { Object.defineProperty(obj, key, { get : function () { console.log("read data: " + val); return val; }, set : function (newVal) { console.log("set data: " + newVal); if(val === newVal){ console.log("val === newVal"); return; } val = newVal; realEstateAgency.publish(); } }) } function observe(obj) { Object.keys(obj).forEach(function (key) { defineReactive(obj, key, obj[key]); }) } observe(house); //publish-subscribe design patten function Subscriber(topics) { this.subs = []; this._topics = topics; } Subscriber.prototype.subscribe = function (sub) { console.log("add sub"); if(this.subs.indexOf(sub) < 0){ this.subs.push(sub); } }; Subscriber.prototype.unsubscribe = function(sub){ console.log("unsubscribe"); for(var i=0; i<this.subs.length; i++){ if(sub === this.subs[i]){ this.subs.splice(i, 1); } } }; Subscriber.prototype.publish = function () { console.log("publish"); var self = this; this.subs.forEach(function (cb) { cb(self._topics); }); }; function Buyer() { this.price = function (housePrice) { console.log("The house price change to: " + housePrice.price); } } var buyer1 = new Buyer(); var buyer2 = new Buyer(); var buyer3 = new Buyer(); var realEstateAgency = new Subscriber(house); realEstateAgency.subscribe(buyer1.price); realEstateAgency.subscribe(buyer2.price); realEstateAgency.subscribe(buyer3.price); house.price = "27000/square meter";
26000/square meter是現在青島市區均價 。。。。