aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/javascript/reference/global_objects/array/unobserve/index.html
blob: 90678a1081083704800b6ac473a00e82b202fe0e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
---
title: Array.unobserve()
slug: Web/JavaScript/Reference/Global_Objects/Array/unobserve
translation_of: Archive/Web/JavaScript/Array.unobserve
---
<div>{{JSRef}} {{non-standard_header}}</div>

<p>Array<strong>.unobserve()方法用来移除</strong>{{jsxref("Array.observe()")}}设置的所有观察者。</p>

<h2 id="语法">语法</h2>

<pre class="syntaxbox"><code>Array.unobserve(<var>arr</var>, <var>callback</var>)</code></pre>

<h3 id="参数">参数</h3>

<dl>
 <dt><code>arr</code></dt>
 <dd>停止观察的数组。</dd>
 <dt> </dt>
 <dt><code>callback回调</code></dt>
 <dd>需要停止的array <strong>arr</strong>每次改变都会调用的函数引用。</dd>
</dl>

<h2 id="描述">描述</h2>

<p><code>Array.unobserve()</code> 方法因为要移除观察者,所以应该在{{jsxref("Array.observe()")}}调用后调用。</p>

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

<h2 id="例子">例子</h2>

<h3 id="停止观察一个数组">停止观察一个数组</h3>

<pre class="brush: js">var arr = [1, 2, 3];

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

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

Array.unobserve(arr, observer);

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

<h3 id="使用匿名函数">使用匿名函数</h3>

<pre class="brush: js">var persons = ['Khalid', 'Ahmed', 'Mohammed'];

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

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

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

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

<h2 id="浏览器兼容性">浏览器兼容性</h2>

<div>
<div>


<p>{{Compat("javascript.builtins.Array.unobserve")}}</p>
</div>
</div>

<h2 id="相关内容">相关内容</h2>

<ul>
 <li>{{jsxref("Array.observe()")}} {{non-standard_inline}}</li>
 <li>{{jsxref("Object.observe()")}} {{non-standard_inline}}</li>
 <li>{{jsxref("Object.unobserve()")}} {{non-standard_inline}}</li>
</ul>