JavaScript实时监听对象属性的改变

Watch.js 1.4.2 Download

关于

Watch.JS是一个有很多可能性的小库。您可能知道,“观察者”设计模式涉及到在观察到的对象发生更改时执行一些函数。其他库也有这样的功能,但是使用Watch.JS就不需要改变开发方式了。看一看示例,看看将Watch.JS添加到代码中有多简单。

兼容以下系列版本的浏览器 ?

Works with: IE 9+, FF 4+, SF 5+, WebKit, CH 7+, OP 12+, BESEN, Node.JS , Rhino 1.7+

安装

HTML Script 标签
<script src="watch.js" type="text/javascript"></script>
<!-- watch will be a global variable -->
Via NPM
npm install melanke-watchjs

Importing

Import as ECMA2015 module
import WatchJS from 'melanke-watchjs';

var watch = WatchJS.watch;
var unwatch = WatchJS.unwatch;
var callWatchers = WatchJS.callWatchers;
Require
var WatchJS = require("melanke-watchjs")
var watch = WatchJS.watch;
var unwatch = WatchJS.unwatch;
var callWatchers = WatchJS.callWatchers;
RequireJS
require("watch", function(WatchJS){
    var watch = WatchJS.watch;
    var unwatch = WatchJS.unwatch;
    var callWatchers = WatchJS.callWatchers;
});

如何使用:

观察一个对象属性的变化

//defining our object however we like
var ex1 = {
	attr1: "initial value of attr1",
	attr2: "initial value of attr2"
};

//defining a 'watcher' for an attribute
watch(ex1, "attr1", function(){
	alert("attr1 changed!");
});

//when changing the attribute its watcher will be invoked
ex1.attr1 = "other value";

观察多个对象属性的更改

//defining our object however we like
var ex2 = {
    attr1: 0,
    attr2: 0,
    attr3: 0
};

//defining a 'watcher' for the attributes
watch(ex2, ["attr2", "attr3"], function(){
    alert("attr2 or attr3 changed!");
});

//when changing one of the attributes its watcher will be invoked
ex2.attr2 = 50;

观察对象所有属性的变化

//defining our object however we like
var ex3 = {
    attr1: 0,
    attr2: "initial value of attr2",
    attr3: ["a", 3, null]
};

//defining a 'watcher' for the object

watch(ex3, function(){
    alert("some attribute of ex3 changes!");
});

//when changing one of the attributes of the object the watcher will be invoked
ex3.attr3.push("new value");

移除 Watcher

var obj = {
    phrase: "hey",
    name: "buddy",
    alert: function(){
        alert(obj.phrase + " " + obj.name);
    },
    alert2: function(){
        alert(obj.name + ", " + obj.phrase);
    }
}
    
watch(obj, "name", obj.alert);
watch(obj, "name", obj.alert2);

obj.name = "johnny";

unwatch(obj, "name", obj.alert);

obj.name = "phil";

有关更改的更多信息

//defining our object no matter which way we want
var ex1 = {
    attr1: "initial value of attr1",
    attr2: "initial value of attr2"
};

//defining a 'watcher' for an attribute
watch(ex1, "attr1", function(prop, action, newvalue, oldvalue){
    alert(prop+" - action: "+action+" - new: "+newvalue+", old: "+oldvalue+"... and the context: "+JSON.stringify(this));
});

//when changing the attribute its watcher will be invoked
ex1.attr1 = "other value";

不要担心无限循环

如果不想在当前范围内调用第二个监视程序,只需设置WatchJS。不再为真,当此监视程序完成时将重置为假。

//以我们喜欢的方式定义对象
var ex1 = {
    attr1: "inicial value of attr1",
    attr2: "initial value of attr2"
};

//为属性定义一个“观察者”
watch(ex1, "attr1", function(){
    WatchJS.noMore = true; //prevent invoking watcher in this scope
    ex1.attr2 = ex1.attr1 + " + 1";
});

//为另一个属性定义其他“观察者”
watch(ex1, "attr2", function(){
    alert("attr2 changed");
});


ex1.attr1 = "other value to 1"; //attr1 will be changed but will not invoke the attr2`s watcher

Try out

你想要多深?提供一个级别的子级

//defining our object no matter which way we want
var ex = {
    //level 0
    l1a: "bla bla",
    l1b: {
        //level 1 or less
        l2a: "lo lo",
        l2b: {
            //level 2 or less
            deeper: "so deep"
        }           
    }
};

watch(ex, function(){
    alert("ex changed at lvl 2 or less");
}, 1);

watch(ex, function(){
    alert("ex changed at lvl 3 or less");
}, 2);


ex.l1b.l2b.deeper = "other value";


ex.l1b.l2b = "other value";

默认情况下,新属性将被忽略

After declaring a watcher for some object, when you add new attributes to this object and/or change it, the watcher will not be invoked.

//defining our object however we like
var ex6 = {
    attr1: 0,
    attr2: 1
};

//defining a 'watcher' for the object
watch(ex6, function(){
    alert("some attribute of ex6 changed!")
});

ex6.attr3 = null; //no watcher will be invoked
ex6.attr3 = "value"; //no watcher will be invoked​​​

您想知道什么时候新属性也会发生更改吗?

这并不完美,你可能要等50毫秒

//defining our object no matter which way we want
var ex = {
    l1a: "bla bla",
    l1b: {
        l2a: "lo lo",
        l2b: "hey hey"        
    }
};

watch(ex, function (prop, action, difference, oldvalue){
    
    alert("prop: "+prop+"\n action: "+action+"\n difference: "+JSON.stringify(difference)+"\n old: "+JSON.stringify(oldvalue)+"\n ... and the context: "+JSON.stringify(this));    
    
}, 0, true);


ex.l1b.l2c = "new attr"; //it is not instantaneous, you may wait 50 miliseconds

setTimeout(function(){
    ex.l1b.l2c = "other value";
}, 100);

随时调用监视程序

//defining our object however we like
var ex7 = {
    attr1: 0,
    attr2: 1
};

//defining a 'watcher' for the object
watch(ex7, function(){
    alert("some attribute of ex6 changed!")
});

callWatchers(ex7, "attr1"); //invoke the watcher​​

与JQuery兼容

$(function(){

    var obj = {cont: 0};
    
    watch(obj, "cont", function(){
        alert("obj.cont = "+obj.cont);
    });

    $("#button").click(function(){
        obj.cont++;
    });
});

构建类/对象和使用Watch.JS的不同方法

//open the browser log to view the messages

var Apple = function(type) {
    var _thisApple = this;
    this.type = type;
    this.color = "red";

    this.getInfo = function() {
        return this.color + ' ' + this.type + ' apple';
    };

    watch(this, function(){
        console.log("although we are using Watch.js the apple structure remains the same");
        for(var i in _thisApple){
            console.log(i+": "+_thisApple[i]);
        }
    });
};


var apple = new Apple("macintosh");
apple.type = "other";


var Banana = function(type) {
    var _thisBanana = this;
    this.type = type;
    this.color = "yellow";

    watch(this, function(){
        console.log("although we are using Watch.js the banana structure remains the same");
        for(var i in _thisBanana){
            console.log(i+": "+_thisBanana[i]);
        }
    });
};

Banana.prototype.getInfo = function() {
    return this.color + ' ' + this.type + ' banana';
};

var banana = new Banana("Cavendish");
banana.type = "other";

var orange = {
    type: "pocan",
    color: "orange",
    getInfo: function () {
        return this.color + ' ' + this.type + ' apple';
    }
};

watch(orange, function(){
    console.log("although we are using Watch.js the orange structure remains the same");

    for(var i in orange){
        console.log(i+": "+orange[i]);
    }
});

orange.type = "other";
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值