VUE 响应式原理- 续

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是现在青岛市区均价 。。。。

猜你喜欢

转载自blog.csdn.net/liubangbo/article/details/85333669