jquery Object.watch()是否适用于所有浏览器?

9bfwbjaz  于 2023-06-05  发布在  jQuery
关注(0)|答案(9)|浏览(455)

请注意,Object.WatchObject.Observe现已弃用(截至2018年6月)。

我一直在寻找一种简单的方法来监视对象或变量的变化,我发现了Object.watch(),Mozilla浏览器支持它,但不支持IE。所以我开始四处寻找,看看是否有人写过类似的东西。
我发现的唯一的东西是a jQuery plugin,但我不确定这是否是最好的方法。我当然在我的大多数项目中使用jQuery,所以我不担心jQuery方面。
不管怎样,问题是:谁能给我展示一下这个jQuery插件的工作示例?我无法让它工作...
或者,有没有人知道任何更好的替代品,将工作跨浏览器?

回答后更新

谢谢大家的回复!我试了一下这里的代码:http://webreflection.blogspot.com/2009/01/internet-explorer-object-watch.html
但我似乎不能让它与IE工作。下面的代码在Firefox中运行良好,但在IE中没有任何作用。在Firefox中,每次更改watcher.status时,都会调用watcher.watch()中的document.write(),您可以在页面上看到输出。在IE中,这不会发生,但我可以看到watcher.status正在更新值,因为最后一次document.write()调用显示了正确的值(在IE和FF中)。但是,如果回调函数没有被调用,那么这就有点无意义了。:)
我错过了什么吗?

var options = {'status': 'no status'},
watcher = createWatcher(options);

watcher.watch("status", function(prop, oldValue, newValue) {
  document.write("old: " + oldValue + ", new: " + newValue + "<br>");
  return newValue;
});

watcher.status = 'asdf';
watcher.status = '1234';

document.write(watcher.status + "<br>");
fruv7luv

fruv7luv1#

(抱歉交叉发布,但我对类似问题的回答在这里很好)
不久前,我为此创建了一个小object.watch shim。它可以在IE8,Safari,Chrome,Firefox,Opera等。

bhmjp9jg

bhmjp9jg2#

该插件只是使用一个定时器/间隔来重复检查对象的更改。也许足够好,但我个人希望作为一个观察者更直接。
以下是将watch/unwatch引入IE的尝试:http://webreflection.blogspot.com/2009/01/internet-explorer-object-watch.html
它确实改变了Firefox添加观察者的语法。而不是:

var obj = {foo:'bar'};
obj.watch('foo', fooChanged);

您需要:

var obj = {foo:'bar'};
var watcher = createWatcher(obj);
watcher.watch('foo', fooChanged);

不是那么甜蜜,但作为一个观察者,你会立即得到通知。

5lhxktic

5lhxktic3#

这个问题的答案有点过时了。Object.watchObject.observe都已弃用,不应使用。
现在,您可以使用Proxy对象来监视(和拦截)对对象所做的更改。下面是一个基本的例子:

var targetObj = {};
var targetProxy = new Proxy(targetObj, {
  set: function (target, key, value) {
      console.log(`${key} set to ${value}`);
      target[key] = value;
      return true;
  }
});

targetProxy.hello_world = "test"; // console: 'hello_world set to test'

如果需要观察对嵌套对象所做的更改,则需要使用专用库。我发布了**Observable Slim**,它是这样工作的:

var test = {testing:{}};
var p = ObservableSlim.create(test, true, function(changes) {
    console.log(JSON.stringify(changes));
});

p.testing.blah = 42; // console:  [{"type":"add","target":{"blah":42},"property":"blah","newValue":42,"currentPath":"testing.blah",jsonPointer:"/testing/blah","proxy":{"blah":42}}]
doinxwow

doinxwow4#

当前答案

使用新的Proxy对象,它可以监视其目标的更改。

let validator = {
    set: function(obj, prop, value) {
        if (prop === 'age') {
            if (!Number.isInteger(value)) {
                throw new TypeError('The age is not an integer');
            }
            if (value > 200) {
                throw new RangeError('The age seems invalid');
            }
        }

        // The default behavior to store the value
        obj[prop] = value;

        // Indicate success
        return true;
    }
};

let person = new Proxy({}, validator);

person.age = 100;
console.log(person.age); // 100
person.age = 'young'; // Throws an exception
person.age = 300; // Throws an exception

2015年的旧答案

您可以使用Object.observe() from ES7Here's a polyfill.但是Object.observe() is now cancelled。对不起的人!

vsnjm48y

vsnjm48y5#

请注意,在Chrome 36及更高版本中,您也可以使用Object.observe。这实际上是未来ECMAScript标准的一部分,而不是像Mozilla的Object.watch那样的特定于浏览器的功能。
Object.observe只对对象属性起作用,但比Object.watch性能更高(Object.watch用于调试目的,而不是生产用途)。

var options = {};

Object.observe(options, function(changes) {
    console.log(changes);
});

options.foo = 'bar';
ktca8awb

ktca8awb6#

你可以使用Object.defineProperty
查看foo中的属性bar

Object.defineProperty(foo, "bar", {
  get: function (val){
      //some code to watch the getter function
  },

  set: function (val) {
      //some code to watch the setter function
  }
})
a5g8bdjr

a5g8bdjr7#

我在一个项目中使用了Watch.js。它运行良好。使用这个库的主要优点之一是:
“有了Watch.JS,你就不必改变你的开发方式了。
下面给出了示例

//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";
<script src="https://cdn.jsdelivr.net/npm/melanke-watchjs@1.5.0/src/watch.min.js"></script>

就这么简单!

yrefmtwq

yrefmtwq8#

这对我很有效

$('#img').hide().attr('src', "path/newImage.jpg").fadeIn('slow');
fzsnzjdm

fzsnzjdm9#

我也认为现在最好的解决方案是使用Watch.JS,在这里找到一个很好的教程:Listen/Watch for object or array changes in Javascript (Property changed event on Javascript objects)

相关问题