JS 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: , 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: , index: 0, removed: [ “Khalid” ], addedCount: 0 }]
Array.unobserve(persons, function (changes) { console.log(changes); });
persons.push(‘Abdullah’); // [{type: “splice”, object: , index: 2, removed: [], addedCount: 1 }] // The callback will always be called