Array.unobserve()

非标准
该特性是非标准的,请尽量不要在生产环境中使用它!

Array.unobserve()方法用来移除Array.observe()设置的所有观察者。

语法

Array.unobserve(arr, callback)

参数

arr
停止观察的数组。
 
callback回调
需要停止的array  arr每次改变都会调用的函数引用。

描述

Array.unobserve() 方法因为要移除观察者,所以应该在Array.observe()调用后调用。

回调函数应该是一个函数的引用并且不能是匿名函数, 因为这个函数需要用来移除前面的观察者, 如果用匿名函数是没有用的,将不能移除任何观察者。

例子

停止观察一个数组

var arr = [1, 2, 3];

var observer = function(changes) {
  console.log(changes);
}

Array.observe(arr, observer);
​
arr.push(4);
// [{type: "splice", object: <arr>, index: 3, removed:[], addedCount: 1}]

Array.unobserve(arr, observer);

arr.pop();
// The callback wasn't called

使用匿名函数

var persons = ['Khalid', 'Ahmed', 'Mohammed'];

Array.observe(persons, function (changes) {
  console.log(changes);
});

persons.shift(); 
// [{type: "splice", object: <arr>, index: 0, removed: [ "Khalid" ], addedCount: 0 }]

Array.unobserve(persons, function (changes) {
  console.log(changes);
});

persons.push('Abdullah');
// [{type: "splice", object: <arr>, index: 2, removed: [], addedCount: 1 }]
// The callback will always be called

浏览器兼容性

Update compatibility data on GitHub
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
unobserve
Deprecated Non-standard
Chrome No support 36 — 52 Edge No support No Firefox No support No IE No support No Opera No support No Safari No support No WebView Android No support No Chrome Android No support No Firefox Android No support No Opera Android No support No Safari iOS No support No Samsung Internet Android No support No nodejs No support No

Legend

No support  
No support
Non-standard. Expect poor cross-browser support.
Non-standard. Expect poor cross-browser support.
Deprecated. Not for use in new websites.
Deprecated. Not for use in new websites.

相关内容