diff options
author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:40:17 -0500 |
---|---|---|
committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:40:17 -0500 |
commit | 33058f2b292b3a581333bdfb21b8f671898c5060 (patch) | |
tree | 51c3e392513ec574331b2d3f85c394445ea803c6 /files/zh-cn/mozilla/javascript_code_modules | |
parent | 8b66d724f7caf0157093fb09cfec8fbd0c6ad50a (diff) | |
download | translated-content-33058f2b292b3a581333bdfb21b8f671898c5060.tar.gz translated-content-33058f2b292b3a581333bdfb21b8f671898c5060.tar.bz2 translated-content-33058f2b292b3a581333bdfb21b8f671898c5060.zip |
initial commit
Diffstat (limited to 'files/zh-cn/mozilla/javascript_code_modules')
13 files changed, 2450 insertions, 0 deletions
diff --git a/files/zh-cn/mozilla/javascript_code_modules/assert.jsm/index.html b/files/zh-cn/mozilla/javascript_code_modules/assert.jsm/index.html new file mode 100644 index 0000000000..a9cbfe6aeb --- /dev/null +++ b/files/zh-cn/mozilla/javascript_code_modules/assert.jsm/index.html @@ -0,0 +1,448 @@ +--- +title: Assert.jsm +slug: Mozilla/JavaScript_code_modules/Assert.jsm +translation_of: Mozilla/JavaScript_code_modules/Assert.jsm +--- +<p>{{ gecko_minversion_header("31") }}</p> + +<p>The <code>Assert.jsm</code> JavaScript code module implements the <a href="http://wiki.commonjs.org/wiki/Unit_Testing/1.1" title="http://wiki.commonjs.org/wiki/Unit_Testing/1.1">CommonJS Unit Testing specification version 1.1</a>, which provides a basic, standardized interface for performing in-code logical assertions with optional, customizable error reporting. To use it, you first need to import the code module into your JavaScript scope:</p> + +<pre class="brush: js">Components.utils.import("resource://testing-common/Assert.jsm"); +</pre> + +<p>Assert 类提供了执行常见逻辑断言的方法。</p> + +<h2 id="Method_overview">Method overview</h2> + +<table class="standard-table"> + <tbody> + <tr> + <td><code><a href="/en-US/JavaScript/Reference/Global_Objects/undefined" title="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/undefined">undefined</a> <a href="#ok()" title="en/JavaScript code modules/Assert.jsm#ok()">ok</a>(value, message);</code></td> + </tr> + <tr> + <td><code><a href="/en-US/JavaScript/Reference/Global_Objects/undefined" title="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/undefined">undefined</a> <a href="#equal()" title="en/JavaScript code modules/Assert.jsm#equal()">equal</a>(actual, expected, message);</code></td> + </tr> + <tr> + <td><code><a href="/en-US/JavaScript/Reference/Global_Objects/undefined" title="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/undefined">undefined</a> <a href="#notEqual()" title="en/JavaScript code modules/Assert.jsm#notEqual()">notEqual</a>(actual, expected, message);</code></td> + </tr> + <tr> + <td><code><a href="/en-US/JavaScript/Reference/Global_Objects/undefined" title="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/undefined">undefined</a> <a href="#deepEqual()" title="en/JavaScript code modules/Assert.jsm#deepEqual()">deepEqual</a>(actual, expected, message);</code></td> + </tr> + <tr> + <td><code><a href="/en-US/JavaScript/Reference/Global_Objects/undefined" title="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/undefined">undefined</a> <a href="#notDeepEqual()" title="en/JavaScript code modules/Assert.jsm#notDeepEqual()">notDeepEqual</a>(actual, expected, message);</code></td> + </tr> + <tr> + <td><code><a href="/en-US/JavaScript/Reference/Global_Objects/undefined" title="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/undefined">undefined</a> <a href="#strictEqual()" title="en/JavaScript code modules/Assert.jsm#strictEqual()">strictEqual</a>(actual, expected, message);</code></td> + </tr> + <tr> + <td><code><a href="/en-US/JavaScript/Reference/Global_Objects/undefined" title="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/undefined">undefined</a> <a href="#notStrictEqual()" title="en/JavaScript code modules/Assert.jsm#notStrictEqual()">notStrictEqual</a>(actual, expected, message);</code></td> + </tr> + <tr> + <td><code><a href="/en-US/JavaScript/Reference/Global_Objects/undefined" title="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/undefined">undefined</a> <a href="#throws()" title="en/JavaScript code modules/Assert.jsm#throws()">throws</a>(block, expected, message);</code></td> + </tr> + <tr> + <td><code><a href="/en/Web/JavaScript/Reference/Global_Objects/Promise" title="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/undefined">Promise</a> <a href="#rejects()" title="en/JavaScript code modules/Assert.jsm#rejects()">rejects</a>(promise, expected, message);</code></td> + </tr> + <tr> + <td><code><a href="/en-US/JavaScript/Reference/Global_Objects/undefined" title="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/undefined">undefined</a> <a href="#greater()" title="en/JavaScript code modules/Assert.jsm#greater()">greater</a>(lhs, rhs, message);</code></td> + </tr> + <tr> + <td><code><a href="/en-US/JavaScript/Reference/Global_Objects/undefined" title="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/undefined">undefined</a> <a href="#greaterOrEqual()" title="en/JavaScript code modules/Assert.jsm#greaterOrEqual()">greaterOrEqual</a>(lhs, rhs, message);</code></td> + </tr> + <tr> + <td><code><a href="/en-US/JavaScript/Reference/Global_Objects/undefined" title="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/undefined">undefined</a> <a href="#less()" title="en/JavaScript code modules/Assert.jsm#less()">less</a>(lhs, rhs, message);</code></td> + </tr> + <tr> + <td><code><a href="/en-US/JavaScript/Reference/Global_Objects/undefined" title="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/undefined">undefined</a> <a href="#lessOrEqual()" title="en/JavaScript code modules/Assert.jsm#lessOrEqual()">lessOrEqual</a>(lhs, rhs, message);</code></td> + </tr> + <tr> + <td><code><a href="/en-US/JavaScript/Reference/Global_Objects/undefined" title="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/undefined">undefined</a> <a href="#setReporter()" title="en/JavaScript code modules/Assert.jsm#setReporter()">setReporter</a>(reporterFunc);</code></td> + </tr> + <tr> + <td><code><a href="/en-US/JavaScript/Reference/Global_Objects/undefined" title="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/undefined">undefined</a> <a href="#report()" title="en/JavaScript code modules/Assert.jsm#report()">report</a>(failed, actual, expected, message, operator);</code></td> + </tr> + </tbody> +</table> + +<h2 id="Constructor">Constructor</h2> + +<p>Creates a new <code>Assert</code> object.</p> + +<pre>let assert = new Assert(reporterFunc); +</pre> + +<p>The new Assert instance, <code>assert</code>, uses <code>reporterFunc</code> to <a href="/en/JavaScript_code_modules/Assert.jsm#report()" title="en/JavaScript code modules/Assert.jsm#report()">report</a> assertion results or throws an <a href="/en/JavaScript_code_modules/Assert.jsm#AssertionError" title="en/JavaScript code modules/Assert.jsm#AssertionError">AssertionError</a> when an assertion fails, as default behavior.</p> + +<p>ok, equal, notEqual, deepEqual, notDeepEqual, strictEqual, notStrictEqual, throws, setReporter, report</p> + +<h2 id="Methods">Methods</h2> + +<h3 id="ok()">ok()</h3> + +<p>Pure assertion tests whether a value is truthy, as determined by !!guard.<br> + This statement is equivalent to <code>assert.<a href="/en/JavaScript_code_modules/Assert.jsm#equal()" title="en/JavaScript code modules/Assert.jsm#equal()">equal</a>(true, !!guard, message_opt);</code>. To test strictly for the value true, use <code>assert.<a href="/en/JavaScript_code_modules/Assert.jsm#strictEqual()" title="en/JavaScript code modules/Assert.jsm#strictEqual()">strictEqual</a>(true, guard, message_opt);</code>.</p> + +<pre>undefined ok( + actual, + message +); +</pre> + +<h6 id="Parameters">Parameters</h6> + +<dl> + <dt><code>actual</code></dt> + <dd>Test subject to be evaluated as truthy</dd> + <dt><code>message</code></dt> + <dd>Short explanation of the expected result</dd> +</dl> + +<h3 id="equal()">equal()</h3> + +<p>The equality assertion tests shallow, coercive equality with ==.</p> + +<pre>undefined equal( + actual, + expected, + message +); +</pre> + +<h6 id="Parameters_2">Parameters</h6> + +<dl> + <dt><code>actual</code></dt> + <dd>Test subject to be evaluated as equivalent to <code>expected</code></dd> + <dt><code>expected</code></dt> + <dd>Test reference to evaluate against <code>actual</code></dd> + <dt><code>message</code></dt> + <dd>Short explanation of the expected result</dd> +</dl> + +<h3 id="notEqual()">notEqual()</h3> + +<p>The non-equality assertion tests for whether two objects are not equal with !=.</p> + +<pre>undefined notEqual( + actual, + expected, + message +); +</pre> + +<h6 id="Parameters_3">Parameters</h6> + +<dl> + <dt><code>actual</code></dt> + <dd>Test subject to be evaluated as <strong>not</strong> equivalent to <code>expected</code></dd> + <dt><code>expected</code></dt> + <dd>Test reference to evaluate against <code>actual</code></dd> + <dt><code>message</code></dt> + <dd>Short explanation of the expected result</dd> +</dl> + +<h3 id="deepEqual()">deepEqual()</h3> + +<p>The equivalence assertion tests a deep equality relation.<br> + We check using the most exact approximation of equality between two objects to keep the chance of false positives to a minimum.<br> + <code>JSON.stringify</code> is not designed to be used for this purpose; objects may have ambiguous <code>toJSON()</code> implementations that would influence the test.</p> + +<pre>undefined deepEqual( + actual, + expected, + message +); +</pre> + +<h6 id="Parameters_4">Parameters</h6> + +<dl> + <dt><code>actual</code></dt> + <dd>Test subject to be evaluated as equivalent to <code>expected</code>, including nested properties</dd> + <dt><code>expected</code></dt> + <dd>Test reference to evaluate against <code>actual</code></dd> + <dt><code>message</code></dt> + <dd>Short explanation of the expected result</dd> +</dl> + +<h3 id="notDeepEqual()">notDeepEqual()</h3> + +<p>The non-equivalence assertion tests for any deep inequality.</p> + +<pre>undefined notDeepEqual( + actual, + expected, + message +); +</pre> + +<h6 id="Parameters_5">Parameters</h6> + +<dl> + <dt><code>actual</code></dt> + <dd>Test subject to be evaluated as <strong>not</strong> equivalent to <code>expected</code>, including nested properties</dd> + <dt><code>expected</code></dt> + <dd>Test reference to evaluate against <code>actual</code></dd> + <dt><code>message</code></dt> + <dd>Short explanation of the expected result</dd> +</dl> + +<h3 id="strictEqual()">strictEqual()</h3> + +<p>The strict equality assertion tests strict equality, as determined by ===.</p> + +<pre>undefined strictEqual( + actual, + expected, + message +); +</pre> + +<h6 id="Parameters_6">Parameters</h6> + +<dl> + <dt><code>actual</code></dt> + <dd>Test subject to be evaluated as strictly equivalent to <code>expected</code></dd> + <dt><code>expected</code></dt> + <dd>Test reference to evaluate against <code>actual</code></dd> + <dt><code>message</code></dt> + <dd>Short explanation of the expected result</dd> +</dl> + +<h3 id="notStrictEqual()">notStrictEqual()</h3> + +<p>The strict non-equality assertion tests for strict inequality, as determined by !==.</p> + +<pre>undefined notStrictEqual( + actual, + expected, + message +); +</pre> + +<h6 id="Parameters_7">Parameters</h6> + +<dl> + <dt><code>actual</code></dt> + <dd>Test subject to be evaluated as <strong>not</strong> strictly equivalent to <code>expected</code></dd> + <dt><code>expected</code></dt> + <dd>Test reference to evaluate against <code>actual</code></dd> + <dt><code>message</code></dt> + <dd>Short explanation of the expected result</dd> +</dl> + +<h3 id="throws()">throws()</h3> + +<p>Expected to throw an error.</p> + +<pre>undefined throws( + block, + expected, + message +); +</pre> + +<h6 id="Parameters_8">Parameters</h6> + +<dl> + <dt><code>block</code></dt> + <dd><a href="/en/JavaScript/Reference/Global_Objects/Function" title="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a> block to evaluate and catch eventual thrown errors</dd> + <dt><code>expected</code></dt> + <dd>Test reference to evaluate against the thrown result from <code>block</code></dd> + <dt><code>message</code></dt> + <dd>Short explanation of the expected result</dd> +</dl> + +<h3 id="rejects()">rejects()</h3> + +<p>Expected to reject a promise. Returns a <a href="/en/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a> that resolves when the promise either resolves or rejects.</p> + +<pre>Promise rejects( + promise, + expected, + message +); +</pre> + +<h6 id="Parameters_9">Parameters</h6> + +<dl> + <dt><code>promise</code></dt> + <dd><a href="/en/Web/JavaScript/Reference/Global_Objects/Promise" title="https://developer.mozilla.org/en/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a> promise to wait for rejection and catch eventual thrown errors</dd> + <dt><code>expected</code></dt> + <dd>Test reference to evaluate against the thrown result from <code>block</code></dd> + <dt><code>message</code></dt> + <dd>Short explanation of the expected result</dd> +</dl> + +<h3 id="greater()">greater()</h3> + +<p>The greater than assertion tests two numbers with the > operator.</p> + +<pre>undefined greater( + lhs, + rhs, + message +); +</pre> + +<h6 id="Parameters_10">Parameters</h6> + +<dl> + <dt><code>lhs</code></dt> + <dd>The left hand side of the operator</dd> + <dt><code>rhs</code></dt> + <dd>The right hand side of the operator</dd> + <dt><code>message</code></dt> + <dd>Short explanation of the expected result</dd> +</dl> + +<h3 id="greaterOrEqual()">greaterOrEqual()</h3> + +<p>The greater or equal than assertion tests two numbers with the >= operator.</p> + +<pre>undefined greaterOrEqual( + lhs, + rhs, + message +); +</pre> + +<h6 id="Parameters_11">Parameters</h6> + +<dl> + <dt><code>lhs</code></dt> + <dd>The left hand side of the operator</dd> + <dt><code>rhs</code></dt> + <dd>The right hand side of the operator</dd> + <dt><code>message</code></dt> + <dd>Short explanation of the expected result</dd> +</dl> + +<h3 id="less()">less()</h3> + +<p>The lesser than assertion tests two numbers with the < operator.</p> + +<pre>undefined less( + lhs, + rhs, + message +); +</pre> + +<h6 id="Parameters_12">Parameters</h6> + +<dl> + <dt><code>lhs</code></dt> + <dd>The left hand side of the operator</dd> + <dt><code>rhs</code></dt> + <dd>The right hand side of the operator</dd> + <dt><code>message</code></dt> + <dd>Short explanation of the expected result</dd> +</dl> + +<h3 id="lessOrEqual()">lessOrEqual()</h3> + +<p>The lesser or equal than assertion tests two numbers with the <= operator.</p> + +<pre>undefined lessOrEqual( + lhs, + rhs, + message +); +</pre> + +<h6 id="Parameters_13">Parameters</h6> + +<dl> + <dt><code>lhs</code></dt> + <dd>The left hand side of the operator</dd> + <dt><code>rhs</code></dt> + <dd>The right hand side of the operator</dd> + <dt><code>message</code></dt> + <dd>Short explanation of the expected result</dd> +</dl> + +<h3 id="setReporter()">setReporter()</h3> + +<p>Set a custom assertion report handler function.</p> + +<pre>undefined setReporter( + reporterFunc +); +</pre> + +<h6 id="Parameters_14">Parameters</h6> + +<dl> + <dt><code>reporterFunc</code></dt> + <dd>Reporter handler <a href="/en/JavaScript/Reference/Global_Objects/Function" title="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">function</a>.<br> + Arguments passed in to this function are: + <dl> + <dt><code>err</code></dt> + <dd>An error object when the assertion failed or null when it passed</dd> + <dt><code>message</code></dt> + <dd>Message describing the assertion</dd> + <dt><code>stack</code></dt> + <dd>Stack trace of the assertion function.</dd> + </dl> + </dd> +</dl> + +<h3 id="report()">report()</h3> + +<p>All of the aforementioned functions must throw an <code>AssertionError</code> when a corresponding condition is not met, with a message that may be <code>undefined</code> if not provided.<br> + All assertion methods provide both the actual and expected values to the assertion error for display purposes.<br> + <br> + This report method only throws errors on assertion failures, as per spec, but consumers of this module (think: xpcshell-test, mochitest) may want to override this default implementation.</p> + +<pre>undefined report( + failed, + actual, + expected, + message, + operator +); +</pre> + +<h6 id="Parameters_15">Parameters</h6> + +<dl> + <dt><code>failed</code></dt> + <dd>Indicates if the assertion failed or not</dd> + <dt><code>actual</code></dt> + <dd>The result of evaluating the assertion</dd> + <dt><code>expected</code></dt> + <dd>Expected result from the test author</dd> + <dt><code>message</code></dt> + <dd>Short explanation of the expected result</dd> + <dt><code>operator</code></dt> + <dd>Operation qualifier used by the assertion method (ex: '==')</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<h3 id="Custom_reporter_example">Custom reporter example</h3> + +<pre class="brush: js">Components.utils.import("resource://testing-common/Assert.jsm"); + +let assert = new Assert(); + +assert.setReporter(function customReporter(err, message, stack) { + if (err) { + do_report_result(false, err.message, err.stack); + } else { + do_report_result(true, message, stack); + } +}); +</pre> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a class="internal" href="/en-US/docs/JavaScript_code_modules/Using" title="en-US/docs/JavaScript code modules/Using JavaScript code modules">Using JavaScript code modules</a></li> + <li><a class="internal" href="/en-US/docs/Mozilla/JavaScript_code_modules" title="en-US/docs/Mozilla/JavaScript code modules">JavaScript code modules</a></li> + <li><a class="internal" href="/en-US/docs/Components.utils.import" title="en-US/docs/Components.utils.import"><code>Components.utils.import</code></a></li> + <li><a href="/en-US/docs/Browser_chrome_tests" title="/en-US/docs/Browser_chrome_tests">Browser Chrome tests</a></li> + <li><a href="/en-US/docs/Mozilla/QA/Writing_xpcshell-based_unit_tests" title="/en-US/docs/Mozilla/QA/Writing_xpcshell-based_unit_tests">Writing xpcshell-based unit tests</a></li> +</ul> diff --git a/files/zh-cn/mozilla/javascript_code_modules/dict.jsm/index.html b/files/zh-cn/mozilla/javascript_code_modules/dict.jsm/index.html new file mode 100644 index 0000000000..b27d445241 --- /dev/null +++ b/files/zh-cn/mozilla/javascript_code_modules/dict.jsm/index.html @@ -0,0 +1,344 @@ +--- +title: Dict.jsm +slug: Mozilla/JavaScript_code_modules/Dict.jsm +translation_of: Mozilla/JavaScript_code_modules/Dict.jsm +--- +<p>{{ gecko_minversion_header("5.0") }}</p> + +<p>{{ warning("This is obsolete - new code should use <code>Map()</code>.") }}</p> + +<p>The <code>Dict.jsm</code> JavaScript code module offers routines for managing dictionaries of key/value pairs. To use it, you first need to import the code module into your JavaScript scope:</p> + +<pre>Components.utils.import("resource://gre/modules/Dict.jsm"); +</pre> + +<h2 id="创建一个字典">创建一个字典</h2> + +<p>You can create a new, empty dictionary by simply calling the <code>Dict()</code> constructor:</p> + +<pre>var newDict = new Dict(); +</pre> + +<p>If you wish, you may also pass in an <a href="/zh-CN/JavaScript/Guide/Values,_variables,_and_literals#Object_literals" title="zh-CN/JavaScript/Guide/Values,_variables,_and_literals#Object_literals">object literal</a> of key/value pairs with which to initialize the dictionary:</p> + +<pre>var someObj = {}; +var newDict = new Dict({key1: "foo", key2: someObj}); +</pre> + +<p>Note that values may be any JavaScript object type.</p> + +<div class="note"><strong>Note:</strong> You can actually specify non-strings as keys; these are converted to strings before being used, so they're documented here as if they were a string parameter.</div> + +<p>从Firefox 19开始,你可以通过传入一个<a href="/zh-CN/JSON" title="zh-CN/JSON">JSON字符串</a>来初始化字典对象:</p> + +<pre>var someJSON = '{key1: "foo", key2: {}}'; +var newDict = new Dict(someJSON); +</pre> + +<div class="note"><strong>注:</strong> 传入的任意字符串都会被当成JSON字符串来对待.</div> + +<h2 id="Method_overview" name="Method_overview">方法概述</h2> + +<table class="standard-table"> + <tbody> + <tr> + <td><code>Dict <a href="/zh-CN/JavaScript_code_modules/Dict.jsm#copy()" title="zh-CN/JavaScript code modules/Dict.jsm#copy()">copy</a>();</code></td> + </tr> + <tr> + <td><code>boolean <a href="/zh-CN/JavaScript_code_modules/Dict.jsm#del()" title="zh-CN/JavaScript code modules/Dict.jsm#del()">del</a>(<a href="/zh-CN/JavaScript/Reference/Global_Objects/String" title="zh-CN/JavaScript/Reference/Global Objects/String">String</a> aKey);</code></td> + </tr> + <tr> + <td><code><a href="/zh-CN/JavaScript/Reference/Global_Objects/Object" title="zh-CN/JavaScript/Reference/Global Objects/Object">Object</a> <a href="/zh-CN/JavaScript_code_modules/Dict.jsm#get()" title="zh-CN/JavaScript code modules/Dict.jsm#get()">get</a>(</code><code><a href="/zh-CN/JavaScript/Reference/Global_Objects/String" title="zh-CN/JavaScript/Reference/Global Objects/String">String</a></code><code> </code><code>aKey</code><code>, [optional] </code><code><a href="/zh-CN/JavaScript/Reference/Global_Objects/Object" title="zh-CN/JavaScript/Reference/Global Objects/Object">Object</a></code><code> aDefault);</code></td> + </tr> + <tr> + <td><code>boolean <a href="/zh-CN/JavaScript_code_modules/Dict.jsm#has()" title="zh-CN/JavaScript code modules/Dict.jsm#has()">has</a>(</code><code><a href="/zh-CN/JavaScript/Reference/Global_Objects/String" title="zh-CN/JavaScript/Reference/Global Objects/String">String</a></code><code> </code><code>aKey</code><code>);</code></td> + </tr> + <tr> + <td><code>Array <a href="/zh-CN/JavaScript_code_modules/Dict.jsm#listitems()" title="zh-CN/JavaScript code modules/Dict.jsm#listitems()">listitems</a>();</code></td> + </tr> + <tr> + <td><code>Array <a href="/zh-CN/JavaScript_code_modules/Dict.jsm#listkeys()" title="zh-CN/JavaScript code modules/Dict.jsm#listkeys()">listkeys</a>();</code></td> + </tr> + <tr> + <td><code>Array <a href="/zh-CN/JavaScript_code_modules/Dict.jsm#listvalues()" title="zh-CN/JavaScript code modules/Dict.jsm#listvalues()">listvalues</a>();</code></td> + </tr> + <tr> + <td><code>void <a href="/zh-CN/JavaScript_code_modules/Dict.jsm#set()" title="zh-CN/JavaScript code modules/Dict.jsm#set()">set</a>(String </code><code>aKey</code><code>, </code><code><a href="/zh-CN/JavaScript/Reference/Global_Objects/Object" title="zh-CN/JavaScript/Reference/Global Objects/Object">Object</a></code><code> aValue);</code></td> + </tr> + <tr> + <td>{{ fx_minversion_inline("19") }} <code><a href="/zh-CN/JavaScript/Reference/Global_Objects/String" title="zh-CN/JavaScript/Reference/Global Objects/String">String</a></code><code> <a href="/zh-CN/JavaScript_code_modules/Dict.jsm#toJSON()" title="zh-CN/JavaScript code modules/Dict.jsm#toJSON()">toJSON</a>();</code></td> + </tr> + <tr> + <td><code><a href="/zh-CN/JavaScript/Reference/Global_Objects/String" title="zh-CN/JavaScript/Reference/Global Objects/String">String</a></code><code> <a href="/zh-CN/JavaScript_code_modules/Dict.jsm#toString()" title="zh-CN/JavaScript code modules/Dict.jsm#toString()">toString</a>();</code></td> + </tr> + </tbody> +</table> + +<h2 id="属性">属性</h2> + +<table class="standard-table" style="width: auto;"> + <tbody> + <tr> + <td class="header">属性名</td> + <td class="header">类型</td> + <td class="header">描述</td> + </tr> + <tr> + <td><code>count</code></td> + <td><a href="/zh-CN/JavaScript/Reference/Global_Objects/Number" title="zh-CN/JavaScript/Reference/Global Objects/Number"><code>Number</code></a></td> + <td>字典中键值对的个数</td> + </tr> + <tr> + <td><code>items</code></td> + <td><code>Iterator</code></td> + <td> + <p>Returns an iterator over all of the items in the dictionary; each item is returned as a pair (a two-element array) with the first element being the key and the second being the value.</p> + + <div class="note"><strong>Note:</strong> The order in which items are returned is arbitrary, and may change without notice. In addition, if the dictionary changes during iteration, no guarantees are made as to what will happen.</div> + </td> + </tr> + <tr> + <td><code>keys</code></td> + <td><code>Iterator</code></td> + <td> + <p>Returns an iterator over all the keys in the dictionary.</p> + + <div class="note"><strong>Note:</strong> The order in which items are returned is arbitrary, and may change without notice. In addition, if the dictionary changes during iteration, no guarantees are made as to what will happen.</div> + </td> + </tr> + <tr> + <td><code>values</code></td> + <td><code>Iterator</code></td> + <td> + <p>Returns an iterator over all the values in the dictionary.</p> + + <div class="note"><strong>Note:</strong> The order in which items are returned is arbitrary, and may change without notice. In addition, if the dictionary changes during iteration, no guarantees are made as to what will happen.</div> + </td> + </tr> + </tbody> +</table> + +<h2 id="构造器">构造器</h2> + +<h2 id="Dict()">Dict()</h2> + +<p>创建并返回一个新的字典对象.</p> + +<pre>Dict Dict(); + +Dict Dict( + Object initalKeysAndValues +); +</pre> + +<h6 id="参数">参数</h6> + +<dl> + <dt><code>initialKeysAndValues</code> {{ optional_inline() }}</dt> + <dd>A object containing key/value pairs with which to initialize the dictionary.</dd> +</dl> + +<h6 id="返回值">返回值</h6> + +<p>一个新的字典对象,实现有下面这些方法.</p> + +<h2 id="Methods" name="Methods">方法</h2> + +<h2 id="copy()">copy()</h2> + +<p>返回一个字典对象的浅拷贝; that is, a copy of the dictionary including the items immediately included within the dictionary; however, any objects referenced by those top-level objects are not copied.</p> + +<pre>Dict copy(); +</pre> + +<h6 id="参数_2">参数</h6> + +<p>无</p> + +<h6 id="返回值_2">返回值</h6> + +<p>A new dictionary object containing the same top-level items as the original dictionary on which the <code>copy()</code> method was called.</p> + +<h2 id="del()">del()</h2> + +<p>根据指定的键,从该字典中删除一个键值对.</p> + +<pre>boolean del( + String aKey +); +</pre> + +<h6 id="参数_3">参数</h6> + +<dl> + <dt><code>aKey</code></dt> + <dd>从该字典中要删除的键.</dd> +</dl> + +<h6 id="返回值_3">返回值</h6> + +<p>如果成功删除指定的键值对,则返回<code>true</code>,如果指定的键不存在,则返回<code>false</code>.</p> + +<h2 id="get()">get()</h2> + +<p>返回该字典对象中指定键所对应的值.</p> + +<pre><code>Object get( + String </code><code>aKey</code><code>, + [optional] Object aDefault +);</code> +</pre> + +<h6 id="参数_4">参数</h6> + +<dl> + <dt><code>aKey</code></dt> + <dd>The key whose value should be returned.</dd> + <dt><code>aDefault</code> {{ optional_inline() }}</dt> + <dd>The value to return if the specified key isn't found. If you don't specify a default value, <code>undefined</code> is returned for keys that aren't found.</dd> +</dl> + +<h6 id="返回值_4">返回值</h6> + +<p>The value of the specified key, or <code>undefined</code> if no matching key was found.</p> + +<h2 id="has()">has()</h2> + +<p>判断指定的键是否存在与当前字典对象中.</p> + +<pre><code>boolean has( + String </code><code>aKey +</code><code>);</code> +</pre> + +<h6 id="参数_5">参数</h6> + +<dl> + <dt><code>aKey</code></dt> + <dd>判断该键是否存在与当前字典对象中..</dd> +</dl> + +<h6 id="返回值_5">返回值</h6> + +<p>如果指定的键存在与当前字典中,则返回<code>true</code>,否则返回<code>false</code>.</p> + +<h2 id="listitems()">listitems()</h2> + +<p>返回一个由当前字典中所有键值对组成的数组.</p> + +<div class="note">注: 数组中元素的排列顺序是任意的.</div> + +<pre>Array listitems(); +</pre> + +<h6 id="参数_6">参数</h6> + +<p>无</p> + +<h6 id="返回值_6">返回值</h6> + +<p>一个由当前字典中所有键值对组成的数组.</p> + +<h2 id="listkeys()">listkeys()</h2> + +<p>返回一个由当前字典中所有键组成的数组.</p> + +<div class="note"><strong>注:</strong> 数组中元素的排列顺序是任意的.</div> + +<pre>Array listkeys(); +</pre> + +<h6 id="参数_7">参数</h6> + +<p>无</p> + +<h6 id="返回值_7">返回值</h6> + +<p>一个由当前字典中所有键组成的数组.</p> + +<h2 id="listvalues()">listvalues()</h2> + +<p>返回一个由当前字典中所有值组成的数组.</p> + +<div class="note"><strong>注:</strong> 数组中元素的排列顺序是任意的.</div> + +<pre>Array listvalues(); +</pre> + +<h6 id="参数_8">参数</h6> + +<p>无</p> + +<h6 id="返回值_8">返回值</h6> + +<p>一个由当前字典中所有值组成的数组.</p> + +<h2 id="set()">set()</h2> + +<p>设置指定键所对应的值,如果该键不存在,则添加上这个新键.</p> + +<pre><code>void set( + String </code><code>aKey</code><code>, + Object aValue +);</code> +</pre> + +<h6 id="参数_9">参数</h6> + +<dl> + <dt><code>aKey</code></dt> + <dd>设置改建所对应的值.</dd> + <dt><code>aValue</code></dt> + <dd>为指定键所设置的新值.</dd> +</dl> + +<h2 id="toJSON()">toJSON()</h2> + +<p>返回一个代表当前字典的 <a href="/zh-CN/JSON" title="zh-CN/JSON">JSON字符串</a>.</p> + +<pre>String toJSON(); +</pre> + +<h6 id="参数_10">参数</h6> + +<p>无</p> + +<h6 id="返回值_9">返回值</h6> + +<p>返回一个代表了该字典对象中所有键值对的JSON字符串,空字典将返回"{}".</p> + +<h2 id="toString()">toString()</h2> + +<p>返回一个代表该字典对象的字符串.</p> + +<pre>String toString(); +</pre> + +<h6 id="参数_11">参数</h6> + +<p>无</p> + +<h6 id="返回值_10">返回值</h6> + +<p>返回一个代表了该字典对象中所有键值对的字符串,空字典将返回"{}".</p> + +<h2 id="示例">示例</h2> + +<h3 id="创建和填充字典">创建和填充字典</h3> + +<p>下面的例子首先创建一个新的空字典,然后添加进一些键值对.</p> + +<pre class="brush: js">var myDict = new Dict(); +myDict.set("name", "John Smith"); +myDict.set("email", "jsmith@example.com"); +myDict.set("phone", "650-555-1234"); +</pre> + +<h3 id="判断字典中指定的键是否存在">判断字典中指定的键是否存在</h3> + +<p>接着上面的个例子,你可以检测某个键是否存在于<code>myDict</code>中:</p> + +<pre class="brush: js">if (myDict.has("email")) { + /* an "email" key exists on the object */ +} +</pre> diff --git a/files/zh-cn/mozilla/javascript_code_modules/downloads.jsm/download/index.html b/files/zh-cn/mozilla/javascript_code_modules/downloads.jsm/download/index.html new file mode 100644 index 0000000000..41230df3c4 --- /dev/null +++ b/files/zh-cn/mozilla/javascript_code_modules/downloads.jsm/download/index.html @@ -0,0 +1,335 @@ +--- +title: Download +slug: Mozilla/JavaScript_code_modules/Downloads.jsm/Download +translation_of: Mozilla/JavaScript_code_modules/Downloads.jsm/Download +--- +<p> <code>Download</code> 对象仅仅表示下载,同时包含相关的状态和行为。这个对象是短时存在的,但是它可被包含在<a href="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadList" title="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadList"><code>DownloadList</code></a> 对象,因此它能够通过用户接口调用和跨sessions.</p> + +<p>调用<a href="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm#createDownload()" title="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm#createDownload()"><code>Downloads.createDownload()</code></a> 方法可以创建一个新的<code>Download</code> 对象。</p> + +<h2 id="方法概览">方法概览</h2> + +<table class="standard-table"> + <tbody> + <tr> + <td><code><a href="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise" title="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise">Promise</a> <a href="#start()">start</a>();</code></td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise" title="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise">Promise</a> <a href="#launch()">launch</a>();</code></td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise" title="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise">Promise</a> <a href="#showContainingDirectory()">showContainingDirectory</a>();</code></td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise" title="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise">Promise</a> <a href="#cancel()">cancel</a>();</code></td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise" title="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise">Promise</a> <a href="#removePartialData()">removePartialData</a>();</code></td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise" title="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise">Promise</a> <a href="#whenSucceeded()">whenSucceeded</a>();</code></td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise" title="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise">Promise</a> <a href="#finalize()">finalize</a>([optional] boolean aRemovePartialData);</code></td> + </tr> + </tbody> +</table> + +<h2 id="属性">属性</h2> + +<table class="standard-table" style="width: auto;"> + <tbody> + <tr> + <td class="header">属性</td> + <td class="header">类型</td> + <td class="header">描述</td> + </tr> + <tr> + <td><code>canceled</code> {{ReadOnlyInline()}}</td> + <td><code>boolean</code></td> + <td> + <p>表示下载被取消。这个属性可设置为true,当被取消下载重新下载时被设置为false。</p> + + <p>This property becomes true as soon as the <a href="#cancel()" title="#cancel()"><code>cancel()</code></a> method is called, though the <code>stopped</code> property might remain false until the cancellation request has been processed. Temporary files or part files may still exist even if they are expected to be deleted, until the <code>stopped</code> property becomes true.</p> + </td> + </tr> + <tr> + <td><code>contentType</code></td> + <td><code>string</code></td> + <td> + <p>The MIME type of the download, for example "<code>text/plain</code>", or <code>null</code> if the MIME type is not available.</p> + + <p>This property may be populated or changed while the download is in progress, using the MIME type provided by the server.</p> + </td> + </tr> + <tr> + <td><code>currentBytes</code> {{ReadOnlyInline()}}</td> + <td><code>number</code></td> + <td> + <p>Number of bytes currently transferred. This value starts at zero, and may be updated regardless of the value of <code>hasProgress</code>.</p> + + <div class="note"><strong>Note:</strong> You shouldn't rely on this property being equal to <code>totalBytes</code> to determine whether the download is completed. You should use the individual state properties instead, since this value may not be updated after the last piece of data is transferred.</div> + </td> + </tr> + <tr> + <td><code>error</code> {{ReadOnlyInline()}}</td> + <td><a href="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadError" title="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadError"><code>DownloadError</code></a></td> + <td>When the download fails, this is set to a <code>DownloadError</code> instance indicating the cause of the failure. If the download has been completed successfully or has been canceled, this property is <code>null</code>. This property is reset to <code>null</code> when a failed download is restarted.</td> + </tr> + <tr> + <td><code>hasPartialData</code> {{ReadOnlyInline()}}</td> + <td><code>boolean</code></td> + <td> + <p>Indicates whether, at this time, there is any partially downloaded data that can be used when restarting a failed or canceled download.</p> + + <p>This property is relevant while the download is in progress, and also if it failed or has been canceled. If the download has been completed successfully, this property is not relevant anymore.</p> + + <p>Whether partial data can actually be retained depends on the saver and the download source, and may not be known before the download is started.</p> + </td> + </tr> + <tr> + <td><code>hasProgress</code> {{ReadOnlyInline()}}</td> + <td><code>boolean</code></td> + <td>Indicates whether this download's <code>progress</code> property is able to report partial progress while the download proceeds, and whether the value in <code>totalBytes</code> is relevant. This depends on the saver and the download source.</td> + </tr> + <tr> + <td><code>launchWhenSucceeded</code></td> + <td><code>boolean</code></td> + <td>If this property is <code>true</code> when the download finishes successfully, the target file will be opened or executed automatically.</td> + </tr> + <tr> + <td><code>launcherPath</code></td> + <td><code>string</code></td> + <td>Local file path of the application to be used to launch the target file, or <code>null</code> if the file should be launched with the default application associated with the <code>contentType</code> property or the extension of the target file.</td> + </tr> + <tr> + <td><code>onchange</code></td> + <td><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function" title="/en-US/docs/JavaScript/Reference/Global_Objects/Function">Function</a></code></td> + <td> + <p>This can be set to a function that is called after other properties change.</p> + + <div class="warning"> + <p><strong>Warning:</strong> This property cannot be used if the download is part of a <a href="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadList" title="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadList"><code>DownloadList</code></a>.</p> + </div> + </td> + </tr> + <tr> + <td><code>progress</code> {{ReadOnlyInline()}}</td> + <td><code>number</code></td> + <td> + <p>Progress percent, from 0 to 100. Intermediate values are reported only if <code>hasProgress</code> is true.</p> + + <div class="note"><strong>Note:</strong> You shouldn't rely on this property being equal to 100 to determine whether the download is completed. You should use the individual state properties (for example, the <code>succeeded</code> property) instead.</div> + </td> + </tr> + <tr> + <td><code>saver</code> {{ReadOnlyInline()}}</td> + <td><code>DownloadSaver</code></td> + <td>Saver object associated with this download.</td> + </tr> + <tr> + <td><code>source</code> {{ReadOnlyInline()}}</td> + <td><a href="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadSource" title="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadSource"><code>DownloadSource</code></a></td> + <td>Source of this download.</td> + </tr> + <tr> + <td><code>startTime</code> {{ReadOnlyInline()}}</td> + <td><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Date" title="/en-US/docs/JavaScript/Reference/Global_Objects/Date"><code>Date</code></a></td> + <td>Indicates the start time of the download. When the download starts, this property is set to a valid <code>Date</code> object. The default value is <code>null</code> before the download starts.</td> + </tr> + <tr> + <td><code>stopped</code> {{ReadOnlyInline()}}</td> + <td><code>boolean</code></td> + <td>Indicates that the download never started, has been completed successfully, failed, or has been canceled. This property becomes <code>false</code> when a download is started for the first time, or when a failed or canceled download is restarted.</td> + </tr> + <tr> + <td><code>succeeded</code> {{ReadOnlyInline()}}</td> + <td><code>boolean</code></td> + <td>This propery is <code>true</code> if the download has been completed successfully.</td> + </tr> + <tr> + <td><code>target</code> {{ReadOnlyInline()}}</td> + <td><a href="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadTarget" title="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadTarget"><code>DownloadTarget</code></a></td> + <td>Target of this download.</td> + </tr> + <tr> + <td><code>totalBytes</code> {{ReadOnlyInline()}}</td> + <td><code>number</code></td> + <td> + <p>When <code>hasProgress</code> is <code>true</code>, this indicates the total number of bytes to be transferred before the download finishes; this value can be zero if the file is empty.</p> + + <p><strong>Note:</strong> This property's value may not match the actual final size of the downloaded file if the download is encoded during the network transfer. You can use the <code>DownloadTarget.size</code> property to get the actual size of the completely-downloaded file once the download has succeeded.</p> + + <p>When <code>hasProgress</code> is <code>false</code>, this property is always zero.</p> + </td> + </tr> + <tr> + <td><code>tryToKeepPartialData</code></td> + <td><code>boolean</code></td> + <td> + <p>Indicates whether any partially downloaded data should be retained, to use when restarting a failed or canceled download. The default is <code>false</code>.</p> + + <p>Whether partial data can actually be retained depends on the saver and the download source, and may not be known before the download is started.</p> + + <p>To have any effect, this property must be set before starting the download. Resetting this property to <code>false</code> after the download has already started will not remove any partial data.</p> + + <div class="note"><strong>Note:</strong> If this property is set to <code>true</code>, care should be taken that partial data is removed before the reference to the download is discarded. This can be done using the <a href="#removePartialData()" title="#removePartialData()"><code>removePartialData()</code></a> or the <a href="#finalize()" title="#finalize()"><code>finalize()</code></a> methods.</div> + </td> + </tr> + </tbody> +</table> + +<h2 id="方法">方法</h2> + +<h3 id="start()">start()</h3> + +<p>Starts the download for the first time, or restarts a download that failed or has been canceled.</p> + +<p>Calling this method when the download has been completed successfully has no effect, and the method returns a resolved promise. If the download is in progress, the method returns the same promise as the previous call.</p> + +<p>If the <code><a href="#cancel()" title="#cancel()">cancel()</a></code> method was called but the cancellation process has not finished yet, this method waits for the cancellation to finish, then restarts the download immediately.</p> + +<div class="note"><strong>Note:</strong> If you need to start a new download from the same source, rather than restarting a failed or canceled one, you should create a separate <code>Download</code> object with the same source as the current one.</div> + +<pre>Promise start(); +</pre> + +<h6 id="Parameters">Parameters</h6> + +<p>None.</p> + +<h6 id="Promise_resolves_to">Promise resolves to</h6> + +<p><code>undefined</code> when the download has finished successfully and you can access the target file.</p> + +<h6 id="Promise_can_be_rejected_with">Promise can be rejected with</h6> + +<p><a href="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadError" title="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadError"><code>DownloadError</code></a> if the download failed.</p> + +<h3 id="launch()">launch()</h3> + +<p>Opens or executes the target file after download has completed.</p> + +<p>If the <code>launcherPath</code> property is <code>null</code>, the file will be opened with the default application for the MIME type specified in the <code>contentType</code> property. If the content type is not available, an attempt will be made to obtain it from the extension of the target file.</p> + +<p>If the <code>launcherPath</code> property is set, the file will be opened with the specified custom application.</p> + +<pre>Promise launch(); +</pre> + +<h6 id="Parameters_2">Parameters</h6> + +<p>None.</p> + +<h6 id="Promise_resolves_to_2">Promise resolves to</h6> + +<p><code>undefined</code> when the instruction to launch the file has been successfully given to the operating system. Note that the OS might still take a while until the file is actually launched.</p> + +<h3 id="showContainingDirectory()">showContainingDirectory()</h3> + +<p>Shows the folder containing the target file, or where the target file will be saved. This may be called at any time, even if the download failed or is currently in progress.</p> + +<pre>Promise showContainingDirectory(); +</pre> + +<h6 id="Parameters_3">Parameters</h6> + +<p>None.</p> + +<h6 id="Promise_resolves_to_3">Promise resolves to</h6> + +<p><code>undefined</code> when the instruction to open the containing folder has been successfully given to the operating system. Note that the OS might still take a while until the folder is actually opened.</p> + +<h3 id="cancel()">cancel()</h3> + +<p>Cancels the download.</p> + +<p>The cancellation request is asynchronous. Until the cancellation process finishes, temporary files or part files may still exist even if they are expected to be deleted.</p> + +<p>In case the download completes successfully before the cancellation request could be processed, this method has no effect, and it returns a resolved promise. You should check the properties of the download at the time the returned promise is resolved to determine if the download was canceled.</p> + +<p>Calling this method when the download has been completed successfully, failed, or has been canceled has no effect, and the method returns a resolved promise. This behavior is designed for the case where the call to <code>cancel</code> happens asynchronously, and is consistent with the case where the cancellation request could not be processed in time.</p> + +<pre>Promise cancel(); +</pre> + +<h6 id="Parameters_4">Parameters</h6> + +<p>None.</p> + +<h6 id="Promise_resolves_to_4">Promise resolves to</h6> + +<p><code>undefined</code> when the cancellation process has finished.</p> + +<h6 id="Promise_can_be_rejected_with_2">Promise can be rejected with</h6> + +<p>Never rejected.</p> + +<h3 id="removePartialData()">removePartialData()</h3> + +<p>Removes any partial data kept as part of a canceled or failed download.</p> + +<p>If the download is not canceled or failed, this method has no effect, and it returns a resolved promise. If the <code><a href="#cancel()" title="#cancel()">cancel()</a></code> method was called but the cancellation process has not finished yet, this method waits for the cancellation to finish, then removes the partial data.</p> + +<p>After this method has been called, if the <code>tryToKeepPartialData</code> property is still <code>true</code> when the download is restarted, partial data will be retained during the new download attempt.</p> + +<pre>Promise removePartialData(); +</pre> + +<h5 id="Parameters_5">Parameters</h5> + +<p>None.</p> + +<h5 id="Promise_resolves_to_5">Promise resolves to</h5> + +<p><code>undefined</code> when the partial data has been successfully removed.</p> + +<h3 id="whenSucceeded()">whenSucceeded()</h3> + +<p>Returns a promise that is resolved as soon as this download finishes successfully, even if the download was stopped and restarted meanwhile.</p> + +<p>You can use this property for scheduling download completion actions in the current session, for downloads that are controlled interactively. If the download is not controlled interactively, you should use the promise returned by the <a href="#start()" title="#start()"><code>start()</code></a> method instead, to check for success or failure.</p> + +<pre>Promise whenSucceeded(); +</pre> + +<h5 id="Parameters_6">Parameters</h5> + +<p>None.</p> + +<h5 id="Promise_resolves_to_6">Promise resolves to</h5> + +<p><code>undefined</code> when the download has finished successfully and you can access the target file.</p> + +<h5 id="Promise_can_be_rejected_with_3">Promise can be rejected with</h5> + +<p>Never rejected.</p> + +<h3 id="finalize()">finalize()</h3> + +<p>Ensures that the download is stopped, and optionally removes any partial data kept as part of a canceled or failed download. After this method has been called, the download cannot be started again.</p> + +<div class="note"><strong>Note:</strong> This method should be used in place of the <code><a href="#cancel()" title="#cancel()">cancel()</a></code> and <a href="#removePartialData()" title="#removePartialData()"><code>removePartialData()</code></a> methods while shutting down or disposing of the download object, to prevent other callers from interfering with the operation. This is required because cancellation and other operations are asynchronous.</div> + +<pre>Promise finalize( + boolean aRemovePartialData +); +</pre> + +<h5 id="Parameters_7">Parameters</h5> + +<dl> + <dt><code>aRemovePartialData</code> {{optional_inline()}}</dt> + <dd>Whether any partially downloaded data should be removed after the download has been stopped. The default is <code>false</code>.</dd> +</dl> + +<h5 id="Promise_resolves_to_7">Promise resolves to</h5> + +<p><code>undefined</code> when the operation has finished successfully.</p> + +<h2 id="查看其他">查看其他</h2> + +<ul> + <li><a href="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm" title="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm">Downloads.jsm</a></li> + <li><a href="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadTarget">DownloadTarget</a></li> +</ul> diff --git a/files/zh-cn/mozilla/javascript_code_modules/downloads.jsm/index.html b/files/zh-cn/mozilla/javascript_code_modules/downloads.jsm/index.html new file mode 100644 index 0000000000..1df73bfd16 --- /dev/null +++ b/files/zh-cn/mozilla/javascript_code_modules/downloads.jsm/index.html @@ -0,0 +1,306 @@ +--- +title: Downloads.jsm +slug: Mozilla/JavaScript_code_modules/Downloads.jsm +tags: + - Add-ons + - Download Manager + - Extensions + - Files + - JavaScript + - Modules + - NeedsTranslation + - TopicStub +translation_of: Mozilla/JavaScript_code_modules/Downloads.jsm +--- +<p>{{ gecko_minversion_header("26") }}</p> + +<p>The <code>Downloads.jsm</code> JavaScript code module provides a single entry point to interact with the downloading capabilities of the platform, including starting new downloads, controlling ongoing downloads, and retrieving download-related configuration. To use it, you first need to import the code module into your JavaScript scope:</p> + +<pre>Components.utils.import("resource://gre/modules/Downloads.jsm"); +</pre> + +<h2 id="Method_overview">Method overview</h2> + +<table class="standard-table"> + <tbody> + <tr> + <td><code><a href="https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise" title="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise">Promise</a><<a href="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/Download" title="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/Download">Download</a>> <a href="#createDownload()">createDownload</a>(<a href="/en-US/docs/JavaScript/Reference/Global_Objects/Object" title="/en-US/docs/JavaScript/Reference/Global_Objects/Object">Object</a> aProperties);</code></td> + </tr> + <tr> + <td><code><a href="https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise" title="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise">Promise</a><void> <a href="#fetch()">fetch</a>(aSource, aTarget, [optional] <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Object" title="/en-US/docs/JavaScript/Reference/Global_Objects/Object">Object</a> </code><code>aOptions);</code></td> + </tr> + <tr> + <td><code><a href="https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise" title="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise">Promise</a><<a href="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadList" title="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadList">DownloadList</a>> <a href="#getList()">getList</a>(aType);</code></td> + </tr> + <tr> + <td><code><a href="https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise" title="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise">Promise</a><<a href="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadSummary" title="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadSummary">DownloadSummary</a>> <a href="#getSummary()">getSummary</a>(aType);</code></td> + </tr> + </tbody> +</table> + +<h2 id="Constants">Constants</h2> + +<table class="standard-table"> + <tbody> + <tr> + <td class="header">Constant</td> + <td class="header">Description</td> + </tr> + <tr> + <td><code>PUBLIC</code></td> + <td>Work on downloads that were not started from a private browsing window.</td> + </tr> + <tr> + <td><code>PRIVATE</code></td> + <td>Work on downloads that were started from a private browsing window.</td> + </tr> + <tr> + <td><code>ALL</code></td> + <td>Work on both <code>Downloads.PRIVATE</code> and <code>Downloads.PUBLIC</code> downloads.</td> + </tr> + </tbody> +</table> + +<h2 id="Properties">Properties</h2> + +<table class="standard-table" style="width: auto;"> + <tbody> + <tr> + <td class="header">Attribute</td> + <td class="header">Type</td> + <td class="header">Description</td> + </tr> + <tr> + <td><code>Error</code> <span class="inlineIndicator readOnly readOnlyInline" title="This value may not be changed.">Read only </span></td> + <td><a href="/en-US/docs/JavaScript/Guide/Working_with_Objects#Using_a_constructor_function" title="/en-US/docs/JavaScript/Guide/Working_with_Objects#Using_a_constructor_function"><code>Constructor</code></a></td> + <td>Constructor for a <a href="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadError" title="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadError"><code>DownloadError</code></a> object. When you catch an exception during a download, you can use this to verify if <code>ex instanceof Downloads.Error</code>, before reading the exception properties with the error details. Example (using <a href="/en-US/docs/Mozilla/JavaScript_code_modules/Task.jsm" title="/en-US/docs/Mozilla/JavaScript_code_modules/Task.jsm"><code>Task.jsm</code></a>): + <pre class="brush: js"> +try { + yield Downloads.fetch(sourceUri, targetFile); +} catch (ex if ex instanceof Downloads.Error && ex.becauseTargetFailed) { + console.log("Unable to write to the target file, ignoring the error."); +}</pre> + </td> + </tr> + </tbody> +</table> + +<h2 id="Methods">Methods</h2> + +<h3 id="createDownload()">createDownload()</h3> + +<p>Creates a new <a href="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/Download" title="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/Download"><code>Download</code></a> object.</p> + +<pre>Promise<Download> createDownload( + Object aProperties +); +</pre> + +<h5 id="Parameters">Parameters</h5> + +<dl> + <dt><code>aProperties</code></dt> + <dd>Provides the initial properties for the newly created download. This matches the serializable representation of a <code><a href="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/Download" title="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/Download">Download</a></code> object. Some of the most common properties in this object include: + <ul> + <li><code>source</code>: String containing the URI for the download source. Alternatively, may be an {{Interface("nsIURI")}}, a <a href="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadSource" title="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadSource"><code>DownloadSource</code></a> object, or an object with the following properties: + <ul> + <li><code>url</code>: String containing the URI for the download source.</li> + <li><code>isPrivate</code>: {{optional_inline()}} Indicates whether the download originated from a private window. If omitted, the download is public.</li> + <li><code>referrer</code>: {{optional_inline()}} String containing the referrer URI of the download source. Can be omitted or <code>null</code> if no referrer should be sent or the download source is not HTTP.</li> + </ul> + </li> + <li><code>target</code>: String containing the path of the target file. Alternatively, may be an {{Interface("nsIFile")}}, a <a href="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadTarget" title="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadTarget"><code>DownloadTarget</code></a> object, or an object with the following properties: + <ul> + <li><code>path</code>: String containing the path of the target file.</li> + </ul> + </li> + <li><code>saver</code>: {{optional_inline()}} String representing the class of the download operation. If omitted, defaults to "copy". Alternatively, may be the serializable representation of a <code>DownloadSaver</code> object.</li> + </ul> + </dd> +</dl> + +<h5 id="Promise_resolves_to">Promise resolves to</h5> + +<p>The newly created <a href="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/Download" title="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/Download"><code>Download</code></a> object.</p> + +<h3 id="fetch()">fetch()</h3> + +<p>Downloads data from a remote network location to a local file.</p> + +<p>This download method does not provide user interface or the ability to cancel or restart the download programmatically. For that, you should obtain a reference to a <a href="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/Download" title="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/Download"><code>Download</code></a> object using the <a href="#createDownload()" title="#createDownload()"><code>createDownload()</code></a> function.</p> + +<p>Since the download cannot be restarted, any partially downloaded data will not be kept in case the download fails.</p> + +<pre>Promise fetch( + aSource, + aTarget, + Object aOptions +); +</pre> + +<h5 id="Parameters_2">Parameters</h5> + +<dl> + <dt><code>aSource</code></dt> + <dd>String containing the URI for the download source. Alternatively, may be an {{Interface("nsIURI")}} or a <a href="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadSource" title="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadSource"><code>DownloadSource</code></a> object.</dd> + <dt><code>aTarget</code></dt> + <dd>String containing the path of the target file. Alternatively, may be an {{Interface("nsIFile")}} or a <a href="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadTarget" title="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadTarget"><code>DownloadTarget</code></a> object.</dd> + <dt><code>aOptions</code> {{optional_inline()}}</dt> + <dd>An optional object used to control the behavior of this function. You may pass an object with a subset of the following fields: + <ul> + <li><code>isPrivate</code>: {{optional_inline()}} Indicates whether the download originated from a private window. If omitted, the download is public.</li> + </ul> + </dd> +</dl> + +<h5 id="Promise_resolves_to_2">Promise resolves to</h5> + +<p><code>undefined</code> when the download has finished successfully and you can access the target file.</p> + +<h5 id="Promise_can_be_rejected_with">Promise can be rejected with</h5> + +<p><a href="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadError" title="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadError"><code>DownloadError</code></a> if the download failed.</p> + +<h3 id="getList()">getList()</h3> + +<p>Retrieves the specified type of <a href="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadList" title="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadList"><code>DownloadList</code></a> object. There is one download list for each type, and this method always retrieves a reference to the same download list when called with the same argument.</p> + +<p>Calling this function may cause the download list to be reloaded from the previous session, if it wasn't loaded already.</p> + +<pre>Promise<DownloadList> getList(aType); +</pre> + +<h5 id="Parameters_3">Parameters</h5> + +<dl> + <dt><code>aType</code></dt> + <dd>This can be <code>Downloads.PUBLIC</code>, <code>Downloads.PRIVATE</code>, or <code>Downloads.ALL</code>. Downloads added to the <code>Downloads.PUBLIC</code> and <code>Downloads.PRIVATE</code> lists are reflected in the <code>Downloads.ALL</code> list, and downloads added to the <code>Downloads.ALL</code> list are also added to either the <code>Downloads.PUBLIC</code> or the <code>Downloads.PRIVATE</code> list based on their properties.</dd> +</dl> + +<h5 id="Promise_resolves_to_3">Promise resolves to</h5> + +<p>The requested <a href="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadList" title="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadList"><code>DownloadList</code></a> object.</p> + +<h3 id="getSummary()">getSummary()</h3> + +<p>Retrieves the specified type of <a href="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadSummary" title="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadSummary"><code>DownloadSummary</code></a> object. There is one download summary for each type, and this method always retrieves a reference to the same download summary when called with the same argument.</p> + +<p>Calling this function does not cause the list of public downloads to be reloaded from the previous session. The summary will behave as if no downloads are present until the <a href="#getList()" title="#getList()"><code>getList()</code></a> method is called.</p> + +<pre>Promise<DownloadSummary> getSummary(aType); +</pre> + +<h5 id="Parameters_4">Parameters</h5> + +<dl> + <dt><code>aType</code></dt> + <dd>This can be <code>Downloads.PUBLIC</code>, <code>Downloads.PRIVATE</code>, or <code>Downloads.ALL</code>.</dd> +</dl> + +<h5 id="Promise_resolves_to_4">Promise resolves to</h5> + +<p>The requested <a href="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadSummary" title="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadSummary"><code>DownloadSummary</code></a> object.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Downloading_to_a_local_file">Downloading to a local file</h3> + +<p>This example downloads an HTML file without showing progress, handling errors programmatically.</p> + +<pre class="brush: js">Components.utils.import("resource://gre/modules/Downloads.jsm"); +Components.utils.import("resource://gre/modules/osfile.jsm") +Components.utils.import("resource://gre/modules/Task.jsm"); + +Task.spawn(function () { + + yield Downloads.fetch("http://www.mozilla.org/", + OS.Path.join(OS.Constants.Path.tmpDir, + "example-download.html")); + + console.log("example-download.html has been downloaded."); + +}).then(null, Components.utils.reportError); +</pre> + +<h3 id="Observing_downloads">Observing downloads</h3> + +<p>This example logs a message every time a change occurs in one of the global download lists.</p> + +<p>To demonstrate the logging, a new download is started while a message box is being shown. The download is stopped and removed from the list when the message box is closed, regardless of whether it has been completed or not.</p> + +<pre class="brush: js">Components.utils.import("resource://gre/modules/Downloads.jsm"); +Components.utils.import("resource://gre/modules/osfile.jsm") +Components.utils.import("resource://gre/modules/Task.jsm"); + +Task.spawn(function () { + + let list = yield Downloads.getList(Downloads.ALL); + + let view = { + onDownloadAdded: download => console.log("Added", download), + onDownloadChanged: download => console.log("Changed", download), + onDownloadRemoved: download => console.log("Removed", download) + }; + + yield list.addView(view); + try { + let download = yield Downloads.createDownload({ + source: "http://www.mozilla.org/", + target: OS.Path.join(OS.Constants.Path.tmpDir, "example-download.html"), + }); + list.add(download); + try { + download.start(); + alert("Now monitoring all downloads. Close the message to stop."); + } finally { + yield list.remove(download); + yield download.finalize(true); + } + } finally { + yield list.removeView(view); + } + +}).then(null, Components.utils.reportError); +</pre> + +<h2 id="Conversion_from_nsIDownloadManager">Conversion from nsIDownloadManager</h2> + +<p>Starting in Firefox for Desktop version 26, the {{interface("nsIDownloadManager")}} and {{interface("nsIDownload")}} interfaces are not available anymore.</p> + +<p>The new module works differently from the old component. In general, you should be aware of the following highlights:</p> + +<ul> + <li>There is no difference between active downloads and finished downloads. The <a href="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/Download" title="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/Download"><code>Download</code></a> object can be used without requiring direct database access.</li> + <li>Observer notifications (for example, <code>"dl-done"</code>) and download listeners are replaced by views on the <a href="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadList" title="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/DownloadList"><code>DownloadList</code></a> object returned by the <a href="#getList()" title="#getList()"><code>getList()</code></a> method.</li> + <li>Object identity replaces the use of numeric identifiers. You can use <a href="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/Download" title="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/Download"><code>Download</code></a> objects as keys in a <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set"><code>Set</code></a> or <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map"><code>Map</code></a> to associate your own state to them for the session.</li> + <li>There is no separate count of active downloads. If a count is needed, it should be maintained using a view on a <code>DownloadList</code>.</li> + <li>The <code><a href="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/Download#start()" title="/en-US/docs/Mozilla/JavaScript_code_modules/Downloads.jsm/Download#start()">start()</a></code> method can be used to restart a failed download. Handling of downloads that have been paused is also different.</li> +</ul> + +<p>While some of the legacy methods and properties have an equivalent in <code>Downloads.jsm</code>, there might be subtle differences in behavior. For example, the properties that handle progress are now more detailed and don't use the special value <code>-1</code> anymore. You may see the documentation of the new methods and properties for details.</p> + +<h2 id="Using_it_in_a_XUL_app">Using it in a XUL app</h2> + +<p>In a XUL standalone application (running with XULRunner or <code>firefox --app</code>), you have to do additionnal things in order to use the new download manager. By default it is not enabled. It will be enabled when the <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=851471">bug 851471</a> will be closed. If you don't activate it, you could use Downloads.jsm, but your view will not be called by the external helper app service (when a user click on a file to download, in a web page). To enable the new download manager :</p> + +<ul> + <li>First you have to set the pref {{pref("browser.download.useJSTransfer")}} to <code>true</code>.</li> + <li>Then you should declare the new {{interface("nsITransfer")}} object during the startup of your app.</li> +</ul> + +<pre> Components.manager.QueryInterface(Components.interfaces.nsIComponentRegistrar) + .registerFactory(Components.ID("{1b4c85df-cbdd-4bb6-b04e-613caece083c}"), "", "@mozilla.org/transfer;1", null); + +</pre> + +<p> </p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a class="internal" href="/en-US/docs/JavaScript_code_modules/Using" title="en-US/docs/JavaScript code modules/Using JavaScript code modules">Using JavaScript code modules</a></li> + <li><a class="internal" href="/en-US/docs/Mozilla/JavaScript_code_modules" title="en-US/docs/Mozilla/JavaScript code modules">JavaScript code modules</a></li> + <li><a class="internal" href="/en-US/docs/Components.utils.import" title="en-US/docs/Components.utils.import"><code>Components.utils.import</code></a></li> +</ul> + +<div id="xunlei_com_thunder_helper_plugin_d462f475-c18e-46be-bd10-327458d045bd"> </div> diff --git a/files/zh-cn/mozilla/javascript_code_modules/geometry.jsm/index.html b/files/zh-cn/mozilla/javascript_code_modules/geometry.jsm/index.html new file mode 100644 index 0000000000..bc18819d7a --- /dev/null +++ b/files/zh-cn/mozilla/javascript_code_modules/geometry.jsm/index.html @@ -0,0 +1,19 @@ +--- +title: Geometry.jsm +slug: Mozilla/JavaScript_code_modules/Geometry.jsm +translation_of: Mozilla/JavaScript_code_modules/Geometry.jsm +--- +<p>{{ gecko_minversion_header("2.0") }}</p> +<p>The <code>Geometry.jsm</code> JavaScript code module provides routines for performing common geometry operations on points and rectangles. It exports two classes: <code>Point</code> and <code>Rect</code>.</p> +<p>To use these routines, you first need to import the code module into your JavaScript scope:</p> +<pre class="eval"><span class="nowiki">Components.utils.import("resource://gre/modules/Geometry.jsm");</span> +</pre> +<p>Once you've imported the module, you can then use the <a href="/zh-CN/JavaScript_code_modules/Geometry.jsm/Point" title="zh-CN/JavaScript code modules/Geometry.jsm/Point"><code>Point</code></a> and <a href="/zh-CN/JavaScript_code_modules/Geometry.jsm/Rect" title="https://developer.mozilla.org/zh-CN/JavaScript_code_modules/Geometry.jsm/Rect"><code>Rect</code></a> classes.</p> +<div class="note"> + <strong>Note:</strong> Although this module is usable from mobile, and is present in Firefox 4, it's currently not used in Firefox 4 and attempting to use it may produce unreliable results there.</div> +<h2 id="See_also">See also</h2> +<ul> + <li><a class="internal" href="/zh-CN/JavaScript_code_modules/Using" title="zh-CN/JavaScript code modules/Using JavaScript code modules">Using JavaScript code modules</a></li> + <li><a class="internal" href="/zh-CN/JavaScript_code_modules" title="zh-CN/JavaScript code modules">JavaScript code modules</a></li> + <li><a class="internal" href="/zh-CN/Components.utils.import" title="zh-CN/Components.utils.import"><code>Components.utils.import</code></a></li> +</ul> diff --git a/files/zh-cn/mozilla/javascript_code_modules/geometry.jsm/services.jsm/index.html b/files/zh-cn/mozilla/javascript_code_modules/geometry.jsm/services.jsm/index.html new file mode 100644 index 0000000000..1acdc77cdf --- /dev/null +++ b/files/zh-cn/mozilla/javascript_code_modules/geometry.jsm/services.jsm/index.html @@ -0,0 +1,25 @@ +--- +title: Services.jsm +slug: Mozilla/JavaScript_code_modules/Geometry.jsm/Services.jsm +translation_of: Mozilla/JavaScript_code_modules/Services.jsm +--- +<p>{{ gecko_minversion_header("2") }}</p> +<p>The <code>Services.jsm</code> 模块提供了一系列的javascript模块,用来简化各种常用的操作.</p> +<p>在使用它们之前,你必须首先将<code>Services</code>模块导入到自己的作用域内:</p> +<pre class="eval"><span class="nowiki">Components.utils.import("resource://gre/modules/Services.jsm");</span> +</pre> +<p>然后你可以通过服务访问器来轻松的从<code>Services对象导出所需要的模块</code>. 例如,要想获取一个preferences服务,你可以用下面的语句:</p> +<pre class="brush: js">var prefsService = Services.prefs; +</pre> +<h2 id="服务访问器">服务访问器</h2> +<table class="standard-table" style="width: auto;"> <tbody> <tr> <td class="header"><span class="short_text" id="result_box" lang="zh-CN"><span>服务</span><span class="alt-edited">访问器</span></span></td> <td class="header">服务接口</td> <td class="header">服务名</td> </tr> <tr> <td><code>appinfo</code></td> <td>{{ interface("nsIXULAppInfo") }}<br> {{ interface("nsIXULRuntime") }}</td> <td>Application information service</td> </tr> + <tr> <td><code>console</code></td> <td>{{ interface("nsIConsoleService") }}</td> <td>Error console service</td> </tr> <tr> <td><code>contentPrefs</code></td> <td>{{ interface("nsIContentPrefService") }}</td> <td> <p>Content Preferences service</p> </td> </tr> <tr> <td><code>cookies</code></td> <td>{{ interface("nsICookieManager2") }}</td> <td> <p>Cookie Manager 2 service</p> </td> </tr> <tr> <td><code>dirsvc</code></td> <td>{{ interface("nsIDirectoryService") }}<br> {{ interface("nsIProperties") }}</td> <td>Directory service</td> </tr> <tr> <td><code>droppedLinkHandler</code></td> <td>{{ interface("nsIDroppedLinkHandler") }}</td> <td>Dropped link handler service</td> </tr> <tr> <td><code>eTLD</code></td> <td>{{ interface("nsIEffectiveTLDService") }}</td> <td> <p>EffectiveTLD service</p> </td> </tr> <tr> <td><code>io</code></td> <td>{{ interface("nsIIOService") }}<br> {{ interface("nsIIOService2") }}</td> <td>I/O Service</td> </tr> <tr> <td><code>locale</code></td> <td>{{ interface("nsILocaleService") }}</td> <td>Locale service</td> </tr> <tr> <td><code>logins</code></td> <td>{{ interface("nsILoginManager") }}</td> <td> <p>Password Manager service</p> </td> </tr> <tr> <td><code>obs</code></td> <td>{{ interface("nsIObserverService") }}</td> <td>Observer service</td> </tr> <tr> <td><code>perms</code></td> <td>{{ interface("nsIPermissionManager") }}</td> <td>Permission manager service</td> </tr> <tr> <td><code>prefs</code></td> <td>{{ interface("nsIPrefBranch") }}<br> {{ interface("nsIPrefBranch2") }}<br> {{ interface("nsIPrefService") }}</td> <td>Preferences service</td> </tr> <tr> <td><code>prompt</code></td> <td>{{ interface("nsIPromptService") }}</td> <td>Prompt service</td> </tr> <tr> <td><code>scriptloader</code></td> <td>{{ interface("mozIJSSubScriptLoader") }}</td> <td>JavaScript subscript loader service</td> </tr> <tr> <td><code>search</code></td> <td>{{ interface("nsIBrowserSearchService") }}</td> <td>Browser search service1</td> </tr> <tr> <td><code>startup</code></td> <td>{{ interface("nsIAppStartup") }}</td> <td>Application startup service</td> </tr> <tr> <td><code>storage</code></td> <td>{{ interface("mozIStorageService") }}</td> <td><a href="/zh-cn/Storage" title="zh-cn/Storage">Storage API</a> service</td> </tr> <tr> <td><code>strings</code></td> <td>{{ interface("nsIStringBundleService") }}</td> <td>String bundle service</td> </tr> <tr> <td><code>sysinfo</code></td> <td>{{ interface("nsIPropertyBag2") }}</td> <td>System info service</td> </tr> <tr> <td><code>telemetry</code></td> <td>{{ interface("nsITelemetry") }}</td> <td>Telemetry service</td> </tr> <tr> <td><code>tm</code></td> <td>{{ interface("nsIThreadManager") }}</td> <td><a href="/zh-cn/The_Thread_Manager" title="zh-cn/The Thread Manager">Thread Manager</a> service</td> </tr> <tr> <td><code>urlFormatter</code></td> <td>{{ interface("nsIURLFormatter") }}</td> <td> <p>URL Formatter service</p> </td> </tr> <tr> <td><code>vc</code></td> <td>{{ interface("nsIVersionComparator") }}</td> <td>Version comparator service</td> </tr> <tr> <td><code>wm</code></td> <td>{{ interface("nsIWindowMediator") }}</td> <td>Window mediator service</td> </tr> <tr> <td><code>ww</code></td> <td>{{ interface("nsIWindowWatcher") }}</td> <td>Window watcher service</td> </tr> <tr> <td><code>DOMRequest</code></td> <td>{{ interface("nsIDOMRequestService") }}</td> <td>DOMRequest service</td> </tr> <tr> <td><code>cpmm</code></td> <td>{{ interface("nsIFrameMessageManager") }}</td> <td>Child Process Message Manager</td> </tr> <tr> <td>ppmm</td> <td>{{ interface("nsIFrameMessageManager") }}</td> <td>Parent Process Message Manager</td> </tr> </tbody> +</table> +<p>Thunderbird 和 SeaMonkey中该特性不可用.</p> +<h2 id="相关链接">相关链接</h2> +<ul> <li><a class="internal" href="/zh-cn/JavaScript_code_modules/Using" title="zh-cn/JavaScript code modules/Using + JavaScript code + modules">Using JavaScript code modules</a></li> <li><a class="internal" href="/zh-cn/JavaScript_code_modules" title="zh-cn/JavaScript code + modules">JavaScript code modules</a></li> <li><a class="internal" href="/zh-cn/XPCOM/mozilla::services_namespace" title="mozilla::services C++ namespace">mozilla::services C++ namespace</a></li> +</ul> +<p>{{ languages( { "en": "en/JavaScript_code_modules/Services.jsm" } ) }}</p> diff --git a/files/zh-cn/mozilla/javascript_code_modules/http.jsm/index.html b/files/zh-cn/mozilla/javascript_code_modules/http.jsm/index.html new file mode 100644 index 0000000000..1e77c4e852 --- /dev/null +++ b/files/zh-cn/mozilla/javascript_code_modules/http.jsm/index.html @@ -0,0 +1,74 @@ +--- +title: Http.jsm +slug: Mozilla/JavaScript_code_modules/Http.jsm +tags: + - API + - HTTP +translation_of: Mozilla/JavaScript_code_modules/Http.jsm +--- +<h2 id="HTTP.jsm">HTTP.jsm</h2> + +<p>Http.jsm 提供了 httpRequest-XMLHttpRequest的包装器,它为处理HTTP请求提供了方便和简化的API。</p> + +<p>httpRequest 支持以下参数:</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">name</th> + <th scope="col">meaning</th> + </tr> + </thead> + <tbody> + <tr> + <td>headers</td> + <td>header 的数组</td> + </tr> + <tr> + <td>postData</td> + <td> + <p>取值范围:</p> + + <ul> + <li>string: 按原样发送</li> + <li>数组: 编码为表单值</li> + <li>null/undefined: 没有POST数据.</li> + </ul> + </td> + </tr> + <tr> + <td> + <p>method</p> + </td> + <td>GET, POST , PUT (如果postData存在,将自动设置).</td> + </tr> + <tr> + <td>onLoad</td> + <td> + <p>加载完成时调用的方法,它接受两个参数:responseText和XHR对象。</p> + </td> + </tr> + <tr> + <td>onError</td> + <td> + <p>当错误发生时调用的方法,它接受三个参数:error、responseText和XHR对象。</p> + </td> + </tr> + <tr> + <td>logger</td> + <td> + <p>实现调试和日志方法的对象(例如log.jsm)。</p> + </td> + </tr> + </tbody> +</table> + +<p>header 或 postData 是作为二维数组给出的,对于每个内部数组,第一个值是键,第二个值是值。例如: [["key1", "value1"], ["key2", "value2"]].</p> + +<h2 id="提交_post_数据">提交 post 数据</h2> + +<p>httpRequest允许向post请求附加数据。可以通过postData选项指定数据。postData可以有两种类型:字符串或数组。当给出null/undefined时,将不发送任何数据。如果给定一个字符串,数据将按原样追加到请求中。如果给定一个参数数组,它将被视为一个键值对数组。数组的元素将采用url编码,并会强制设置content type为“application/x-www-form-urlencoded;charset=utf-8"。Http.jsm只在post数据是数组时强行设置content type,并自动序列化它。如果提供的postdata是一个字符串,则不设置内容类型。在这种情况下,可以通过header参数设置content type。</p> + +<h2 id="可选的XHR_配置">可选的XHR 配置</h2> + +<p>在调用httpRequest之后,可以手动修改XHR对象上的内容。httpRequest返回一个XHR对象,该对象可用于设置请求的附加参数。例如,可以将XHR配置为在处理响应时使用任何自定义mime类型,而不管服务器返回什么。为此,可以通过调用httpRequest获得XHR对象,然后调用它的<a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#overrideMimeType%28%29">overrideMimeType()</a>方法去设置MIME-Type。另一个<a href="http://mxr.mozilla.org/comm-central/source/chat/protocols/twitter/twitter.js#690">例子</a>可以在这里找到。</p> diff --git a/files/zh-cn/mozilla/javascript_code_modules/index.html b/files/zh-cn/mozilla/javascript_code_modules/index.html new file mode 100644 index 0000000000..415663945b --- /dev/null +++ b/files/zh-cn/mozilla/javascript_code_modules/index.html @@ -0,0 +1,84 @@ +--- +title: JavaScript 代码模块 +slug: Mozilla/JavaScript_code_modules +tags: + - Add-ons(加载项) + - JavaScript + - TopicStub + - XPCOM + - mo + - 扩展 + - 模块 +translation_of: Mozilla/JavaScript_code_modules +--- +<p>{{Non-standard_Header}}</p> + +<div class="blockIndicator note"> +<p><strong>注意:</strong> JavaScript代码模块和JavaScript 标准中的模块(module)不是一回事。 要学习如何使用标准中的模块,请点击 {{JSxRef("Statements/export", "export")}} 和 {{JSxRef("Statements/import", "import")}} 查看。</p> +</div> + +<p>JavaScript 代码模块用于具备不同权限的作用域之间的代码共享。例如,Firefox 可以使用模块,也可以通过扩展来使用模块,以避免重复代码。</p> + +<table class="topicpage-table"> + <tbody> + <tr> + <td> + <h2 id="话题总览">话题总览</h2> + + <dl> + <dt><a href="/en-US/docs/JavaScript_code_modules/Using" title="./Using">使用JavaScript代码模块</a></dt> + <dd>介绍如何使用JavaScript代码模块</dd> + <dt><a href="/en-US/docs/Components.utils.import" title="Components.utils.import">Component.utils.import</a></dt> + <dd>如何导入一个JavaScript的代码模块。</dd> + <dt><a href="/en-US/docs/Components.utils.unload" title="Components.utils.unload">Component.utils.unload</a> {{gecko_minversion_inline("7.0")}}</dt> + <dd>如何上传一个JavaScript的代码模块</dd> + <dt><a href="/en-US/docs/Code_snippets/Modules" title="Code_snippets/Modules">代码片段: Module</a></dt> + <dd>如何使用模块代码的实例。</dd> + <dt><a class="external" href="http://wiki.mozilla.org/Labs/JS_Modules">Mozilla实验室的 JS Modules</a></dt> + <dd>本页面列出了JS模块的列表,以及下载链接和文档,扩展开发人员可以在代码中使用它们。</dd> + </dl> + + <dl> + </dl> + </td> + <td> + <h2 id="标准代码模块">标准代码模块</h2> + + <dl> + <dt><a href="/en-US/docs/Mozilla/js-ctypes" title="./ctypes.jsm">ctypes.jsm</a> {{fx_minversion_inline("3.6")}}</dt> + <dd>提供一个允许JS代码在不需要开发一个XPCOM元素的前提下调用本地库的接口。</dd> + <dt><a href="/en-US/docs/JavaScript_code_modules/FileUtils.jsm" title="./FileUtils.jsm"><strong style="font-weight: bold;">FileUtils.jsm</strong></a> {{gecko_minversion_inline("1.9.2")}}</dt> + <dd>提供处理文件的有用的方法</dd> + <dt><a href="/en-US/docs/JavaScript_code_modules/Geometry.jsm" title="JavaScript code modules/Geometry.jsm">Geometry.jsm</a> {{gecko_minversion_inline("2.0")}}</dt> + <dd>提供用于对点和矩形执行基本几何操作的方法。</dd> + <dt><a href="/en-US/docs/JavaScript_code_modules/ISO8601DateUtils.jsm" title="./ISO8601DateUtils.jsm">ISO8601DateUtils.jsm</a></dt> + <dd>提供在JavaScript <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Date" title="JavaScript/ Reference/Global Objects/Date"><code>Date</code></a> 对象和ISO 8601 data字符串之间转换的方法。</dd> + <dt><a href="/en-US/docs/JavaScript_code_modules/Dict.jsm" title="JavaScript code modules/Dict.jsm">Dict.jsm</a> {{gecko_minversion_inline("5.0")}}</dt> + <dd>提供一个可以访问键值对词典的API。</dd> + <dt><a href="/en-US/docs/JavaScript_code_modules/NetUtil.jsm" title="./NetUtil.jsm"><strong style="font-weight: bold;">NetUtil.jsm</strong></a></dt> + <dd>提供一些有用的网络实用函数,使您能够轻松地将输入流中的数据异步复制到输出流的。</dd> + <dt><a href="/en-US/docs/JavaScript_code_modules/PopupNotifications.jsm" title="JavaScript code modules/PopupNotifications.jsm">PopupNotifications.jsm</a> {{gecko_minversion_inline("2.0")}}</dt> + <dd>提供一种给用户弹出非模态(non-modal)通知的简便方法</dd> + <dt><a href="/en-US/docs/JavaScript_code_modules/openLocationLastURL.jsm" title="./openLocationLastURL.jsm">openLocationLastURL.jsm</a> {{gecko_minversion_inline("1.9.1.4")}}</dt> + <dd>提供读取使用文件菜单中的“打开定位(Open Location)” 时打开的最后一个URL的能力。</dd> + <dt><a href="/en-US/docs/JavaScript_code_modules/DownloadLastDir.jsm" title="JavaScript/Code modules/DownloadLastDir.jsm">DownloadLastDir.jsm</a> {{gecko_minversion_inline("2.0")}}</dt> + <dd>提供最后一次下载时的目录路径。</dd> + <dt><a href="/en-US/docs/Localization_and_Plurals" title="Localization and Plurals">PluralForm.jsm</a></dt> + <dd>提供获取当前区域使用的正确的复数形式的一种简便方法,当然也可以使用一种指定的复数规则来将一个词语复数化。</dd> + <dt><a href="/en-US/docs/JavaScript_code_modules/Services.jsm" title="./Services.jsm">Services.jsm</a> {{gecko_minversion_inline("2.0")}}</dt> + <dd>提供getter来方便地获取对一些常用服务的访问。</dd> + <dt><a href="/en-US/docs/JavaScript_code_modules/source-editor.jsm" title="JavaScript_code_modules/source-editor.jsm">source-editor.jsm</a> {{fx_minversion_inline("11.0")}}</dt> + <dd>源编辑器(Souce Editor)是指那些you开发者工具所提供的编辑器,如样式编辑器;此接口实现了源编辑器,并且允许你与之交互。</dd> + <dt><a href="/en-US/docs/JavaScript_code_modules/XPCOMUtils.jsm" title="./XPCOMUtils.jsm">XPCOMUtils.jsm</a></dt> + <dd>包含一些为JS组件加载器所加载的JavaScript组件的实用程序。</dd> + <dt><a href="/en-US/docs/JavaScript_code_modules/PerfMeasurement.jsm" title="JavaScript/Code_modules/PerfMeasurement.jsm">PerfMeasurement.jsm</a> {{fx_minversion_inline("4.0")}}</dt> + <dd>提供对底层硬件和操作系统性能测量工具的访问。</dd> + <dt><a href="/en-US/docs/Addons/Add-on_Manager" title="Addons/Add-on_Manager">AddonManager.jsm</a> {{gecko_minversion_inline("2.0")}}</dt> + <dd>安装、管理和卸载加载项(add-ons)的接口。</dd> + <dt><a href="/en-US/docs/Addons/Add-on_Repository" title="Addons/Add-on Repository">AddonRepository.jsm</a> {{gecko_minversion_inline("2.0")}}</dt> + <dd>允许搜索加载项(add-ons)列表。</dd> + </dl> + </td> + </tr> + </tbody> +</table> diff --git a/files/zh-cn/mozilla/javascript_code_modules/promise.jsm/deferred/index.html b/files/zh-cn/mozilla/javascript_code_modules/promise.jsm/deferred/index.html new file mode 100644 index 0000000000..aa0d921e0c --- /dev/null +++ b/files/zh-cn/mozilla/javascript_code_modules/promise.jsm/deferred/index.html @@ -0,0 +1,190 @@ +--- +title: Deferred +slug: Mozilla/JavaScript_code_modules/Promise.jsm/Deferred +translation_of: Mozilla/JavaScript_code_modules/Promise.jsm/Deferred +--- +<p> <code>Deferred</code> 对象返回了一个已经被废弃的方法<code>Promise.defer()</code> 并提供给新的promise用来改变promise的状态。</p> + +<p>从Gecko 30开始,该对象就已经被废弃,并建议不再使用。可以通过 <a href="/Mozilla/JavaScript_code_modules/Promise.jsm/Promise#Constructor" title="/Mozilla/JavaScript_code_modules/Promise.jsm/Promise#Constructor"><code>new Promise()</code></a> 构造新的promise取代,(或者使用向后/向前兼容的Deferred方法实现,如下:)。等价方法如下: </p> + +<pre class="brush: js">var deferred = Promise.defer(); +doSomething(function cb(good) { + if (good) + deferred.resolve(); + else + deferred.reject(); +}); +return deferred.promise;</pre> + +<p>应写成:</p> + +<pre class="brush: js">return new Promise(function(resolve, reject) { + doSomething(function cb(good) { + if (good) + resolve(); + else + reject(); + }); +});</pre> + +<h2 id="方法概览">方法概览</h2> + +<table class="standard-table"> + <tbody> + <tr> + <td><code>void <a href="#resolve()">resolve</a>([optional] aValue);</code></td> + </tr> + <tr> + <td><code>void <a href="#reject()">reject</a>([optional] aReason);</code></td> + </tr> + </tbody> +</table> + +<h2 id="属性">属性</h2> + +<table class="standard-table" style="width: auto;"> + <tbody> + <tr> + <td class="header">Attribute</td> + <td class="header">Type</td> + <td class="header">Description</td> + </tr> + <tr> + <td><code>promise</code> {{ReadOnlyInline()}}</td> + <td><a href="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise" title="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise"><code>Promise</code></a></td> + <td>新创建的promise,在pending阶段被初始化</td> + </tr> + </tbody> +</table> + +<h2 id="方法">方法</h2> + +<h3 id="resolve()">resolve()</h3> + +<p>将指定的值赋给新建的promise,或者改变已存在的 promise 状态。如果关联的 promise 已经调用过 resolve 方法,无论是传入值、rejection,或另一个 promise,此方法都不会起效果。</p> + +<div class="note"><strong>Note:</strong> This function is bound to its associated promise when <a href="https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm#defer()" title="https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm#defer()"><code>Promise.defer()</code></a> is called, and can be called with any value of <code>this</code>.</div> + +<div class="note"><strong>Note:</strong> Calling this method with a pending promise as the <code>aValue</code> argument, and then calling it again with another value before the promise is resolved or rejected, will have no effect the second time, as the associated promise is already resolved to the pending promise value as its resolution.</div> + +<pre>void resolve( + aValue +); +</pre> + +<h6 id="Parameters">Parameters</h6> + +<dl> + <dt><code>aValue</code> <span class="inlineIndicator optional optionalInline">Optional</span></dt> + <dd>If this value is not a promise, including <code>undefined</code>, it becomes the fulfillment value of the associated promise. If this value is a promise, then the associated promise will be resolved to the passed promise, and follow the state as the provided promise (including any future transitions).</dd> +</dl> + +<h3 id="reject()">reject()</h3> + +<p>Rejects the associated promise with the specified reason. If the promise has already been resolved, either to a value, a rejection, or another promise, this method does nothing.</p> + +<div class="note"><strong>Note:</strong> This function is bound to its associated promise when <a href="https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm#defer()" title="https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm#defer()"><code>Promise.defer()</code></a> is called, and can be called with any value of <code>this</code>.</div> + +<pre>void reject( + aReason +); +</pre> + +<h6 id="Parameters_2">Parameters</h6> + +<dl> + <dt><code>aReason</code> <span class="inlineIndicator optional optionalInline">Optional</span></dt> + <dd> + <p>The rejection reason for the associated promise. Although the reason can be <code>undefined</code>, it is generally an <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Error" title="/en-US/docs/JavaScript/Reference/Global_Objects/Error"><code>Error</code></a> object, like in exception handling.</p> + + <div class="note"><strong>Note:</strong> This argument should not be a promise. Specifying a rejected promise would make the rejection reason equal to the rejected promise itself, and not its rejection reason.</div> + </dd> +</dl> + +<h2 id="Backwards_and_forwards_compatible_helper">Backwards and forwards compatible helper<a id="backwards_forwards_compatible" name="backwards_forwards_compatible"></a></h2> + +<p>This Deferred function can be used for backwards and forwards compatibility, due to a change that took place in Firefox 30.</p> + +<pre>function Deferred() { + // update 062115 for typeof + if (typeof(Promise) != 'undefined' && Promise.defer) { + //need import of Promise.jsm for example: Cu.import('resource:/gree/modules/Promise.jsm'); + return Promise.defer(); + } else if (typeof(PromiseUtils) != 'undefined' && PromiseUtils.defer) { + //need import of PromiseUtils.jsm for example: Cu.import('resource:/gree/modules/PromiseUtils.jsm'); + return PromiseUtils.defer(); + } else { + /* A method to resolve the associated Promise with the value passed. + * If the promise is already settled it does nothing. + * + * @param {anything} value : This value is used to resolve the promise + * If the value is a Promise then the associated promise assumes the state + * of Promise passed as value. + */ + this.resolve = null; + + /* A method to reject the assocaited Promise with the value passed. + * If the promise is already settled it does nothing. + * + * @param {anything} reason: The reason for the rejection of the Promise. + * Generally its an Error object. If however a Promise is passed, then the Promise + * itself will be the reason for rejection no matter the state of the Promise. + */ + this.reject = null; + + /* A newly created Promise object. + * Initially in pending state. + */ + this.promise = new Promise(function(resolve, reject) { + this.resolve = resolve; + this.reject = reject; + }.bind(this)); + Object.freeze(this); + } +}</pre> + +<p>and use this function as would Promise.defer:</p> + +<pre class="brush: js">function funcWithDefer() { + var deferred = new Deferred(); + var promise = deferred.promise; + promise.then( + function(aVal) { + console.log('Fullfilled - ', aVal); + }, + function(aReason) { + console.error('Rejected - aReason:', aReason) + } + ); + + //deferred.resolve('aVal of resolved'); + deferred.reject('reject val'); + + return promise; +} + +var promise_funcWithDefer = funcWithDefer(); +promise_funcWithDefer.then( + function(aVal) { + console.log('Fullfilled - promise_funcWithDefer - ', aVal); + }, + function(aReason) { + var refObj = {name:'promise_funcWithDefer', aReason:aReason}; + console.error('Rejected - promise_funcWithDefer - ', refObj); + } +).catch( + function(aCatch) { + console.error('Caught - promise_funcWithDefer - ', aCatch); + throw aCatch; + } +);</pre> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm" title="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm">Promise.jsm</a></li> +</ul> + +<p> + <audio style="display: none;"> </audio> +</p> diff --git a/files/zh-cn/mozilla/javascript_code_modules/promise.jsm/index.html b/files/zh-cn/mozilla/javascript_code_modules/promise.jsm/index.html new file mode 100644 index 0000000000..a02f5f0385 --- /dev/null +++ b/files/zh-cn/mozilla/javascript_code_modules/promise.jsm/index.html @@ -0,0 +1,172 @@ +--- +title: Promise.jsm +slug: Mozilla/JavaScript_code_modules/Promise.jsm +tags: + - NeedsTranslation + - TopicStub +translation_of: Mozilla/JavaScript_code_modules/Promise.jsm +--- +<p>{{ gecko_minversion_header("25") }}</p> +<p>The <code>Promise.jsm</code> JavaScript code module implements the <a href="https://github.com/promises-aplus/promises-spec/blob/1.0.0/README.md" title="https://github.com/promises-aplus/promises-spec/blob/1.0.0/README.md">Promises/A+</a> proposal as known in April 2013. To use it, you first need to import the code module into your JavaScript scope:</p> +<pre>Components.utils.import("resource://gre/modules/Promise.jsm"); +</pre> +<div class="note"> + <p><strong>Note:</strong> A preliminary promise module is also available starting from Gecko 17, though it didn't conform to the Promises/A+ proposal until Gecko 25:</p> + <pre>Components.utils.import("<strike>resource://gre/modules/commonjs/promise/core.js</strike>"); // Gecko 17 to 20 +Components.utils.import("<strike>resource://gre/modules/commonjs/sdk/core/promise.js</strike>"); // Gecko 21 to 24 +</pre> + <p>This implementation also includes helper functions that are specific to the Add-on SDK. While you may still import this module from the above paths, the recommended way for loading it is through the <a href="https://addons.mozilla.org/en-US/developers/docs/sdk/latest/modules/toolkit/loader.html" title="https://addons.mozilla.org/en-US/developers/docs/sdk/latest/modules/toolkit/loader.html">Add-on SDK loader</a>.</p> +</div> +<h2 id="Introduction">Introduction</h2> +<p>For an introduction to promises, you may start from the <a class="external" href="https://addons.mozilla.org/en-US/developers/docs/sdk/latest/modules/sdk/core/promise.html" title="https://addons.mozilla.org/en-US/developers/docs/sdk/1.9/packages/api-utils/promise.html">Add-on SDK documentation</a>, keeping in mind that only the core subset is implemented in this module.</p> +<p><u>A promise is an object representing a value that may not be available yet</u>. Internally, a promise can be in one of three states:</p> +<ul> + <li><strong>Pending</strong>, when the final value is not available yet. This is the only state that may transition to one of the other two states.</li> + <li><strong>Fulfilled</strong>, when and if the final value becomes available. A <em>fulfillment value</em> becomes permanently associated with the promise. This may be any value, including <code>undefined</code>.</li> + <li><strong>Rejected</strong>, if an error prevented the final value from being determined. A <em>rejection reason</em> becomes permanently associated with the promise. This may be any value, including <code>undefined</code>, though it is generally an <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Error" title="/en-US/docs/JavaScript/Reference/Global_Objects/Error"><code>Error</code></a> object, like in exception handling.</li> +</ul> +<p>A reference to an existing promise may be received by different means, for example as the return value of a call into an asynchronous API. In this case, the state of the promise can be observed but not directly controlled.</p> +<p>To observe the state of a promise, its <code>then</code> method must be used. This method registers callback functions that are called as soon as the promise is either fulfilled or rejected. The method returns a new promise, that in turn is fulfilled or rejected depending on the state of the original promise and on the behavior of the callbacks. For example, unhandled exceptions in the callbacks cause the new promise to be rejected, even if the original promise is fulfilled. See the documentation of the <code>then</code> method for details.</p> +<p>Promises may also be created using the <a href="#defer()" title="#defer()"><code>Promise.defer()</code></a> function, the main entry point of this module. The function, along with the new promise, returns separate methods to resolve or reject the promise. See the documentation of the <a href="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Deferred" title="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Deferred"><code>Deferred</code></a> object for details.</p> +<h2 id="Method_overview">Method overview</h2> +<table class="standard-table"> + <tbody> + <tr> + <td><code><a href="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Deferred" title="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Deferred">Deferred</a> <a href="#defer()">defer</a>();</code></td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise" title="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise">Promise</a> <a href="#resolve()">resolve</a>([optional] aValue);</code></td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise" title="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise">Promise</a> <a href="#reject()">reject</a>([optional] aReason);</code></td> + </tr> + </tbody> +</table> +<h2 id="Methods">Methods</h2> +<h3 id="defer()">defer()</h3> +<p>Creates a new pending promise and provides methods to resolve or reject it.</p> +<pre>Deferred defer(); +</pre> +<h6 id="Parameters">Parameters</h6> +<p>None.</p> +<h6 id="Return_value">Return value</h6> +<p>A new object, containing the new promise in the <code>promise</code> property, and the methods to change its state in the <code>resolve</code> and <code>reject</code> properties. See the <a href="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Deferred" title="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Deferred"><code>Deferred</code></a> documentation for details.</p> +<h3 id="resolve()">resolve()</h3> +<p>Creates a new promise fulfilled with the specified value, or propagates the state of an existing promise.</p> +<pre>Promise resolve( + aValue +); +</pre> +<h6 id="Parameters_2">Parameters</h6> +<dl> + <dt> + <code>aValue</code> {{ optional_inline() }}</dt> + <dd> + If this value is not a promise, including <code>undefined</code>, it becomes the fulfillment value of the returned promise. If this value is a promise, then the returned promise will be resolved with the value, i.e. it will eventually assume the same state as the provided promise.</dd> +</dl> +<h6 id="Return_value_2">Return value</h6> +<p>A promise that can be pending, fulfilled, or rejected.</p> +<h3 id="reject()">reject()</h3> +<p>Creates a new promise rejected with the specified reason.</p> +<pre>Promise reject( + aReason +); +</pre> +<h6 id="Parameters_3">Parameters</h6> +<dl> + <dt> + <code>aReason</code> {{ optional_inline() }}</dt> + <dd> + <p>The rejection reason for the returned promise. Although the reason can be <code>undefined</code>, it is generally an <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Error" title="/en-US/docs/JavaScript/Reference/Global_Objects/Error"><code>Error</code></a> object, like in exception handling.</p> + <div class="note"> + <strong>Note:</strong> This argument should not be a promise. Specifying a rejected promise would make the rejection reason equal to the rejected promise itself, and not its rejection reason.</div> + </dd> +</dl> +<h6 id="Return_value_3">Return value</h6> +<p>A rejected promise.</p> +<h2 id="Examples">Examples</h2> +<pre class="brush: js">Components.utils.import("resource://gre/modules/Promise.jsm"); + +// This function creates and returns a new promise. +function promiseValueAfterTimeout(aValue, aTimeout) +{ + let deferred = Promise.defer(); + + try { + // An asynchronous operation will trigger the resolution of the promise. + // In this example, we don't have a callback that triggers a rejection. + setTimeout(function () { + deferred.resolve(aValue); + }, aTimeout); + } catch (ex) { + // Generally, functions returning promises propagate exceptions through + // the returned promise, though they may also choose to fail early. + deferred.reject(ex); + } + + // We don't return the deferred to the caller, but only the contained + // promise, so that the caller cannot accidentally change its state. + return deferred.promise; +} + +// This code uses the promise returned be the function above. +let promise = promiseValueAfterTimeout("Value", 1000); + +let newPromise = promise.then(function onFulfill(aValue) { + console.log("Fulfilled with this value: " + aValue); +}, function onReject(aReason) { + console.log("Rejected with this reason: " + aReason); +}); + +// Unexpected errors should always be reported at the end of a promise chain. +newPromise.then(null, Components.utils.reportError);</pre> +<div class="note"> + <strong>Note:</strong> More examples for consuming promises are available in the <a href="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise" title="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise">Promise object documentation</a>.</div> +<h2 id="The_case_of_unhandled_rejections">The case of unhandled rejections</h2> +<p>One of the difficult problems with promises is locating uncaught rejections.</p> +<div class="warning"> + <p><strong>Warning:</strong> When consuming promises, you should always handle or report errors (rejection reasons). See <a href="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise#Handling_errors_and_common_pitfalls" title="#Handling_errors_and_common_pitfalls">handling errors and common pitfalls</a>.</p> +</div> +<p>Rejection handlers provide information about the exact error time and location, but the handlers may sometimes be forgotten. Consider the following cases:</p> +<pre class="brush: js" style="text-align: justify;">function f() { + return Promise.reject(new Error("BOOM!")); // If nobody catches the error, how will it be reported? +} + + +function g() { + return Promise.resolve().then(function() { + throw new Error("BOOM!"); // If nobody catches the error, how will it be reported? + }); +} + +function h() { + Promise.reject(new Error("BOOM!"); // Oops, we forgot to return the promise, nobody can catch it! +} +</pre> +<p>We adopt the following strategy: if a promise is rejected at the time of its garbage-collection <strong>and</strong> if the promise is at the end of a promise chain (i.e. <code>thatPromise.then</code> has never been called), then we print a warning.</p> +<div class="note"> + <strong>Note:</strong> This warning is generated some time after the error occurred, and may provide less information about the error location. It generally indicates the need to insert a proper error handler. When a proper rejection handler is used, it effectively replaces this delayed reporting.</div> +<pre class="brush: js">let deferred = Promise.defer(); +let p = deferred.promise.then(); +deferred.reject(new Error("I am an uncaught error")); +deferred = null; +p = null;</pre> +<p><br> + In this snippet, since <code>deferred.promise</code> is not the last in the chain, no error will be reported for that promise. However, since <code>p</code> is the last promise in the chain, the error will be reported for <code>p</code>.<br> + <br> + Note that this may, in some cases, cause an error to be reported more than once. For instance, consider:</p> +<pre class="brush: js">let deferred = Promise.defer(); +let p1 = deferred.promise.then(); +let p2 = deferred.promise.then(); +deferred.reject(new Error("I am an uncaught error")); +p1 = p2 = deferred = null;</pre> +<p><br> + In this snippet, the error is reported both at <code>p1</code> and at <code>p2</code>.</p> +<h2 id="See_also">See also</h2> +<ul> + <li><a href="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise" title="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise">Promise</a></li> + <li><a href="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Deferred" title="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Deferred">Deferred</a></li> + <li><a class="internal" href="/en-US/docs/JavaScript_code_modules/Using" title="en-US/docs/JavaScript code modules/Using JavaScript code modules">Using JavaScript code modules</a></li> + <li><a class="internal" href="/en-US/docs/Mozilla/JavaScript_code_modules" title="en-US/docs/Mozilla/JavaScript code modules">JavaScript code modules</a></li> + <li><a class="internal" href="/en-US/docs/Components.utils.import" title="en-US/docs/Components.utils.import"><code>Components.utils.import</code></a></li> +</ul> diff --git a/files/zh-cn/mozilla/javascript_code_modules/promise.jsm/promise/index.html b/files/zh-cn/mozilla/javascript_code_modules/promise.jsm/promise/index.html new file mode 100644 index 0000000000..947fd3acdc --- /dev/null +++ b/files/zh-cn/mozilla/javascript_code_modules/promise.jsm/promise/index.html @@ -0,0 +1,226 @@ +--- +title: Promise +slug: Mozilla/JavaScript_code_modules/Promise.jsm/Promise +translation_of: Mozilla/JavaScript_code_modules/Promise.jsm/Promise +--- +<p><strong>Promise对象代表暂时不可用的值。</strong></p> + +<p>一个已存在的promise引用可以通过不同的方式被接收,如作为异步API的返回值。一旦得到一个promise对象,就可以调用其 <a href="#then()" title="#then()"><code>then()</code></a> 方法,以在其值可用时或者出现异常时执行一个动作。</p> + +<p>可以通过 <a href="https://developer.mozilla.org/zh-CN/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise$edit#Constructor" title="#Constructor"><code>new Promise()</code></a><code> </code>方法创建Promise对象,当使用一个已存在的Promise对象时,不需要引入 <a href="https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm" title="#defer()"><code>Promise.jsm</code></a> 模块。</p> + +<p>promise内部状态可为以下三种之一:</p> + +<ul> + <li><strong>未完成状态(pending)</strong>,此时完成值还不可用,它是唯一一个能够转换为其他状态的状态。</li> + <li><strong>已完成状态(fulfilled)</strong>,此时<em>完成值</em>可用,完成值与promise永久绑定,可为任意值,包括<code>undefined。</code></li> + <li><strong>拒绝状态(rejected)</strong>,出现错误时,<em>拒绝理由</em>与promise永久绑定,可为任意值,包括<code>undefined</code>,一般情况下为 <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Error" title="/en-US/docs/JavaScript/Reference/Global_Objects/Error"><code>Error</code></a> 对象。</li> +</ul> + +<div class="note"> +<p><strong>备注: </strong>使用promise时,应该始终对异常(拒绝理由)进行处理或报告。如果你看见了"<strong>A promise chain failed to handle a rejection</strong>"的错误信息,你可能就需要检查你的代码。参见下面的 <a href="https://developer.mozilla.org/zh-CN/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise$edit#Handling_errors_and_common_pitfalls">异常处理和常见误区</a>。</p> +</div> + +<h2 id="文档约定">文档约定</h2> + +<p>文档规定,完成值的类型通过尖括号内的内容指定。如 <code style="font-style: normal;"><a href="/en-US/docs/JavaScript_OS.File/OS.File_for_the_main_thread#OS.File.exists()" title="/en-US/docs/JavaScript_OS.File/OS.File_for_the_main_thread#OS.File.exists()">OS.File.exists</a></code> 方法返回一个完成值类型为<code>boolean</code>的promise:</p> + +<pre>Promise<boolean> exists(string path); +</pre> + +<p>拒绝理由可能在function文档中单独规定,除非特别指定,一般使用 <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Error" title="/en-US/docs/JavaScript/Reference/Global_Objects/Error"><code>Error</code></a> 对象作为拒绝理由。</p> + +<h2 id="方法概览">方法概览</h2> + +<table> + <tbody> + <tr> + <td><code>Promise <a href="https://developer.mozilla.org/zh-CN/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise$edit#then()">then</a>([optional] <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function" title="/en-US/docs/JavaScript/Reference/Global_Objects/Function">Function</a> onFulfill, </code><code>[optional] </code><code><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function" title="/en-US/docs/JavaScript/Reference/Global_Objects/Function">Function</a> onReject</code><code>);</code></td> + </tr> + <tr> + <td><code>Promise <a href="https://developer.mozilla.org/zh-CN/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise$edit#catch">catch</a>([optional] <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function">Function</a> onReject);</code></td> + </tr> + </tbody> +</table> + +<h2 id="构造函数">构造函数</h2> + +<p>创建一个新的promise,初始化为等待状态,并提供解决函数的引用,用于改变其状态。</p> + +<pre><code>new Promise(executor);</code></pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code>executor</code></dt> + <dd> + <p>该函数会马上被调用,它带有两个参数的函数对象:</p> + + <p> </p> + </dd> + <dd> + <pre><code>executor(resolve, reject);</code></pre> + + <p>构造函数直到执行完成才会返回。解决函数可以在任何时间被调用,在执行过程完成前后都可以,其目标是控制promise的最终状态。如果执行过程抛出异常,异常值会被传递到reject解决函数中。</p> + </dd> +</dl> + +<h3 id="解决函数">解决函数</h3> + +<h4 id="resolve()">resolve()</h4> + +<p>用特定值满足绑定的promise,或者把状态传递到一个已存在的promise。如果绑定的promise已经被解决(可能是一个值,也可能是一个rejection,或者是另一个promise),该方法不会做任何事。</p> + +<div class="note"> +<p><strong>备注:</strong> 调用该方法时,如果用一个pending状态的promise作为aValue参数,然后在该promise状态改变为fullfilled或者rejected前用另一个值再次调用,第二次调用将不会生效,因为这个绑定的promise已经被pending promise所解决了。</p> +</div> + +<pre><code>void resolve( + aValue +);</code></pre> + +<h6 id="参数_2">参数</h6> + +<dl> + <dt><code>aValue</code> 可选</dt> + <dd>如果这个值不是一个promise,包括 <code>undefined</code>, 它会变成绑定promise的实现值。如果这个值是promise,绑定promise会被传递的promise解决,并跟随所提供的promise的状态(包括任何未来的转变)。</dd> +</dl> + +<h4 id="reject()">reject()</h4> + +<p>用特定原因拒绝绑定的promise。如果promise已经被解决了,不管是值,拒绝,还是另一个promise,这个方法都不会做任何事。</p> + +<pre><code>void reject( + aReason +);</code></pre> + +<h6 id="参数_3">参数</h6> + +<dl> + <dt><code>aReason</code> 可选</dt> + <dd>绑定promise的拒绝原因。通常是一个 <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Error">Error</a> 对象,就像在异常处理那样,尽管理由也可以是 <code>undefined。</code></dd> +</dl> + +<div class="note"> +<p><strong>备注:</strong> 该参数不应该是promise。要说明一个被拒绝的promise,应该让拒绝原因等于被拒绝promise自身,而非其拒绝原因。</p> +</div> + +<h2 id="方法">方法</h2> + +<h3 id="then()">then()</h3> + +<p><span style="line-height: 1.5;">一旦promise完成或被拒绝,就立即执行一个回调函数,并返回一个新的promise对象,新promise的状态取决于promise和传入的回调函数</span></p> + +<div>回调函数始终会在<code>then</code>返回值后被调用,即使promise早已完成或已被拒绝。也可对多次调用同一个promise的<code>then</code>方法。所有的回调函数会按照其注册的顺序被调用。</div> + +<p> </p> + +<div class="warning"> +<p><strong>警告</strong>: 如果 <code>onFulfill</code> 抛出异常,不会调用 <code>onReject</code> ,异常也不会被捕获和输出到控制台(你会看到一个promise chain失败错误),可以在返回的promise上注册一个错误处理函数,以处理在任一回调中出现的异常(使用 catch() 或者 then() ),来处理发生在任何一个注册回调函数的异常。</p> +</div> + +<p> </p> + +<div class="note"> +<p><strong>注意</strong>:当多次调用同一个promise的then方法,所有注册的回调函数独立执行。如,当在一个回调函数中出现异常时,不会影响后面回调函数的执行。回调函数的结果只会对其注册所使用的then方法返回的promise产生影响,每一次调用then方法返回的都是不同的promise对象。</p> +</div> + +<pre>Promise then( + Function onFulfill, + Function onReject +); +</pre> + +<h6 id="参数_4">参数</h6> + +<dl> + <dt><code>onFulfill</code> {{optional_inline()}}</dt> + <dd>当promise完成时,会调用该函数,并将完成值作为其唯一参数传入,该函数的输出会决定新的promise的状态。如果该参数不是函数(通常为<code>null</code>),则由then返回的新的promise的状态为已完成,且完成值与原promise相同</dd> + <dt><code>onReject</code> {{optional_inline()}}</dt> + <dd> + <p>当promise被拒绝时,会调用该函数,并将拒绝理由作为其唯一参数传入,且该函数的输出会决定新的promise的状态。如果该参数不是函数(通常为<code>undefined</code>),则由<code>then</code>返回的新的promise的状态为拒绝,且拒绝理由与原promise相同。</p> + </dd> +</dl> + +<h6 id="返回值">返回值</h6> + +<p>新的promise对象,初始状态为未完成,最终状态取决于回调函数的输出:</p> + +<ul> + <li> + <div>如果返回的不是promise,包括<code>undefined</code>,则新promise的状态为已完成,并将该返回值作为其完成值,即使原promises被拒绝</div> + </li> + <li> + <div><span style="line-height: 1.5;">如果抛出异常,则新的promise的状态为拒绝,并将该异常作为其拒绝理由,即使原promise已完成</span></div> + </li> + <li> + <div><span style="line-height: 1.5;">如果返回promise,则新promise的最终状态与回调函数返回的promise状态相同。</span></div> + </li> +</ul> + +<div> +<h3 id="catch()"><a name="catch">catch()</a></h3> + +<p>等价于调用<code>onFulfill参数为undefined的</code> <code>then()</code> 方法。如果你链式调用then( onFulfill ).catch( onReject ),onFulfill中抛出的异常会被捕捉并传递到onReject。</p> + +<pre><code>Promise catch( + Function onReject +);</code></pre> + +<p>等价于以下调用:</p> + +<pre><code>p.then(undefined, logError); +p.catch(logError);</code></pre> +</div> + +<div> </div> + +<h2 id="调试">调试</h2> + +<p>按照设计,在不调用 <code style="font-style: normal;"><a href="#then()" title="#then()">then()</a></code>的情况下,promise的即时状态和值不能通过代码同步检测到。</p> + +<p>为了有助于调试,只有当手动检查promise时,才能看到那些不能通过代码访问的特殊属性的信息(目前由于缺少复杂的语言或调试器的支持,属性名是随机生成的)。</p> + +<p>这些代码可访问和可审查的属性有:</p> + +<ul> + <li><code><strong><span>{</span>{private:status}}</strong></code>: 0代表未完成,1代表已完成,2代表拒绝。</li> + <li><code><strong><span>{</span>{private:value}}</strong></code>:完成值或拒绝理由,仅在promise已完成或已拒绝时有值。</li> + <li><code><strong><span>{</span>{private:handlers}}</strong></code>: 对象数组,这些对象保存了对回调函数的引用,仅在未完成状态下可用。</li> +</ul> + +<p style="text-align: center;"><img alt="Promise properties are visible in the debugger." src="https://mdn.mozillademos.org/files/6471/Promise-Debug-1.png" style="border-style: solid; border-width: 2px; height: 482px; margin-bottom: 15px; margin-top: 15px; width: 403px;"><img alt="Promise handlers can be watched from the Console." src="https://mdn.mozillademos.org/files/6473/Promise-Debug-2.png" style="border-style: solid; border-width: 2px; height: 161px; width: 977px;"></p> + +<h2 id="示例">示例</h2> + +<p id="如何抛出拒绝">请看 <a href="https://developer.mozilla.org/Mozilla/JavaScript_code_modules/Promise.jsm/Examples">示例</a> 页面.</p> + +<h2 id="异常处理和常见误区">异常处理和常见误区</h2> + +<p>promise应该报告未处理的错误,除非交给其他程序处理该错误。</p> + +<pre class="brush: js">// ###### WRONG: Silently drops any rejection notified by "OS.File.Exists". +OS.File.exists(path).then(exists => { if (exists) myRead(path); }); + +// ###### WRONG: Silently drops any exception raised by "myRead". +OS.File.exists(path).then(exists => { if (exists) myRead(path); }, Components.utils.reportError); + +// CORRECT (for example, might report the exception "myRead is not defined") +OS.File.exists(path).then(exists => { if (exists) myRead(path); }) + .catch(null, Components.utils.reportError); + +// CORRECT (the function returns a promise, and the caller will handle the rejection) +function myReadIfExists(path) +{ + return OS.File.exists(path).then(exists => { if (exists) myRead(path); }); +}</pre> + +<h2 id="参见">参见</h2> + +<ul> + <li><a href="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm" title="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm">Promise.jsm</a></li> + <li><a href="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Deferred" title="/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Deferred">Deferred</a></li> + <li><a href="/en-US/docs/JavaScript_OS.File" title="/en-US/docs/JavaScript_OS.File">JavaScript OS.File</a></li> + <li><a href="http://kryogenix.org/days/2013/12/12/promises-promises">Promises, Promises</a>: a useful simple explanation by Stuart Langridge</li> + <li><a href="http://dom.spec.whatwg.org/#promises">WHATWG Living Standard</a></li> +</ul> diff --git a/files/zh-cn/mozilla/javascript_code_modules/timer.jsm/index.html b/files/zh-cn/mozilla/javascript_code_modules/timer.jsm/index.html new file mode 100644 index 0000000000..83ae26b154 --- /dev/null +++ b/files/zh-cn/mozilla/javascript_code_modules/timer.jsm/index.html @@ -0,0 +1,33 @@ +--- +title: Timer.jsm +slug: Mozilla/JavaScript_code_modules/Timer.jsm +tags: + - JavaScript + - JavaScript计时器 + - 插件 + - 模块 +translation_of: Mozilla/JavaScript_code_modules/Timer.jsm +--- +<p>{{ gecko_minversion_header("22") }}</p> + +<p>Timer.jsm JavaScript模块包含纯JavaScript对<a href="/en-US/docs/DOM/window.setTimeout" title="/en-US/docs/DOM/window.setTimeout"><code>setTimeout</code></a>、<code><a href="/en-US/docs/DOM/window.clearTimeout" title="/en-US/docs/DOM/window.clearTimeout">clearTimeout</a><font face="Open Sans, Arial, sans-serif">、</font></code><code><a href="/en-US/docs/Web/API/WindowTimers/setInterval">setInterval</a></code>和<a href="/en-US/docs/Web/API/WindowTimers/clearInterval"><code>clearInterval</code></a>功能的实现且适用于DOM窗口函数,但它还可以被那些无法访问DOM窗口的代码(如<a href="/en-US/docs/Mozilla/JavaScript_code_modules" title="/en-US/docs/Mozilla/JavaScript_code_modules">JavaScript模块</a>或<a href="/en-US/docs/The_message_manager" title="/en-US/docs/The_message_manager">框架里的脚本</a>)使用。</p> + +<p> </p> + +<p><code><font face="Open Sans, Arial, sans-serif">要使用</font>Timer.jsm,首先导入它:</code></p> + +<pre class="brush: js">Components.utils.import("resource://gre/modules/Timer.jsm"); +</pre> + +<p>然后如同在DOM窗口中一样使用setTimeout和clearTimeout,例如:</p> + +<pre class="brush: js">let timeoutID = setTimeout(function() { console.log("Hello!"); }, 500); + +clearTimeout(timeoutID); +</pre> + +<p>类似地,你可以使用<code>setInterval和</code><code>clearInterval,比如:</code></p> + +<pre class="brush: js">let intervalID = setInterval(function() { console.log("Happening every 500ms!"); }, 500); + +clearInterval(intervalID);</pre> diff --git a/files/zh-cn/mozilla/javascript_code_modules/using/index.html b/files/zh-cn/mozilla/javascript_code_modules/using/index.html new file mode 100644 index 0000000000..41fdf9970e --- /dev/null +++ b/files/zh-cn/mozilla/javascript_code_modules/using/index.html @@ -0,0 +1,194 @@ +--- +title: 使用 JavaScript 代码 modules 模式 +slug: Mozilla/JavaScript_code_modules/Using +tags: + - Add-ons + - Extensions + - Guide + - JavaScript + - XPCOM +translation_of: Mozilla/JavaScript_code_modules/Using +--- +<p>{{ gecko_minversion_header("1.9") }}</p> + +<p>JavaScript code modules 在Gecko1.9中引入并被用于具备不同权限的作用域之间的代码共享。 Modules 也可以用于创建全局js单例,这在之前是通过使用XPCOM(跨平台组件模型)实现的。一个 JavaScript code module 是仅仅是位于注册位置的一些 JavaScript 代码。Module 被载入特定的js域,比如 XUL script or JavaScript XPCOM script, 通过<code><a href="/en/Components.utils.import" title="en/Components.utils.import">Components.utils.import()</a></code> or <code><a href="/en/Components.utils.import" title="en/Components.utils.import">Components.utils["import"]()</a></code>.</p> + +<h2 id="创建_JavaScript_code_module">创建 JavaScript code module</h2> + +<p>一个简单的例子my_module.jsm:</p> + +<pre class="brush: js notranslate" style="width: 900px;">var EXPORTED_SYMBOLS = ["foo", "bar"]; + +function foo() { + return "foo"; +} + +var bar = { + name : "bar", + size : 3 +}; + +var dummy = "dummy"; +</pre> + +<p>可以看到 module 使用规范的js语言来创建函数,对象,常量以及其他的数据类型。 Module 还定义了一个名为 <code>EXPORTED_SYMBOLS 的特殊数组,这个数组中的每一项都会被输出到声明中并且被注入到引入的作用域中。例如:</code></p> + +<pre class="brush: js notranslate">Components.utils.import("resource://app/my_module.jsm"); + +alert(foo()); // displays "foo" +alert(bar.size + 3); // displays "6" +alert(dummy); // displays "dummy is not defined" because 'dummy' was not exported from the module +</pre> + +<div class="note"><strong>Note:</strong> When you're testing changes to a code module, be sure to change the application's build ID (e.g. the version) before your next test run; otherwise, you may find yourself running the previous version of your code module's code still.</div> + +<h3 id="The_URL_for_a_code_module">The URL for a code module</h3> + +<p>正如你在上例中看到的, 你需要一个 URL 来导入一个代码块 (code module)。 (就像例子中的 "<a class="external" rel="freelink">resource://app/my_module.jsm</a>".)</p> + +<p>有三种模式的URL可供选择: <strong>chrome:……</strong>({{ gecko_minversion_inline("2") }}), <strong>resource:……</strong>, 或者 <strong>file:……</strong>.</p> + +<ul> + <li>如果你在为 Firefox 4 写一个扩展并且已经有了一个 <a href="/en/Chrome_Registration" title="en/Chrome registration">chrome.manifest</a>(里面是内容指示), 你可以将代码块 code module 放入你的内容文件夹并通过<code>chrome://<yourextension>/content/<yourmodule>.jsm指向它。</code></li> + <li>如果你的扩展或应用需要支持 Mozilla 1.9.x (Firefox 3.x), 你需要注册一个新的资源URL. 具体细节在这: <a href="#resource-urls">"Extending resource: URLs" section</a> .</li> +</ul> + +<h3 id="通过code_modules共享对象">通过code modules共享对象</h3> + +<p><code><a href="/en/Components.utils.import" title="en/Components.utils.import">Components.utils.import()</a></code> 的一个非常重要行为就是 module 加载后会被缓存起来, 并且随后的的导入不会重新加载一个新版的module, 而是使用之前缓存的版本。这就意味着当导入 module 多次时, 一个给定的 module 会被共享多次。只要引入某个module,任何对数据,对象和函数的变化都会体现在不同的引入该module的域中。比如,一个简单的module被引入到两个不同的域中,在其中一个域中做改变,另一个域也共享这种改变。如下例 :</p> + +<p>Scope 1:</p> + +<pre class="brush: js notranslate">Components.utils.import("resource://app/my_module.jsm"); + +alert(bar.size + 3); // displays "6" + +bar.size = 10; +</pre> + +<p>Scope 2:</p> + +<pre class="brush: js notranslate">Components.utils.import("resource://app/my_module.jsm"); + +alert(foo()); // displays "foo" +alert(bar.size + 3); // displays "13" +</pre> + +<p>这种共享行为可以被用来创建单例对象(singleton objects)并且可以被 跨windows 和 XUL script 和 XPCOM 组件所共享。</p> + +<p>注意:引入某个module的域获得了一组该module中定义的输出符号的按值复制的副本( by-value copy )。 对这些输出符号的改变或者重新定义不会传播到其他的域中。 (虽然对象的属性会通过引用来改变。)。例子如下:</p> + +<p>Scope 1:</p> + +<pre class="brush: js notranslate">Components.utils.import("resource://app/my_module.jsm"); + +bar = "foo"; +alert(bar); // displays "foo" +</pre> + +<p>Scope 2:</p> + +<pre class="brush: js notranslate">Components.utils.import("resource://app/my_module.jsm"); + +alert(bar); // displays "[object Object]" +</pre> + +<p>按值复制的主要效果就是简单类型的全局变量不会在不同的域之间共享。所以我们经常将变量放在大括号中,然后以对象的形式输出 (就像上例中的bar)。</p> + +<p>{{ h2_gecko_minversion("Unloading code modules", "7.0") }}</p> + +<p><code><a href="/en/Components.utils.unload" title="en/Components.utils.unload">Components.utils.unload()</a></code> 允许你卸载之前引入的module。该方法被调用后, 指向该module的引用可以继续工作,但是后续对该module的引入,就会重新加载并重新分配指向该module的引用值。</p> + +<h2 id="Extending_resource_URLs">Extending resource: URLs</h2> + +<p>{{ Gecko("2.0") }}之前,加载code module最常用的方式是—— <strong>resource:</strong> URLs. Resource URL 的基本语法如下:</p> + +<pre class="eval notranslate">resource://<alias>/<relative-path>/<file.js|jsm> +</pre> + +<p><code><alias></code> 是某个位置的别称,通常是一个相对于应用程序或者 XUL runtime的物理位置。这是一些由XUL runtime设置的预定义的别称:</p> + +<ul> + <li><code>app</code> - XUL application 位置的别名</li> + <li><code>gre</code> - XUL runtime 位置的别名</li> +</ul> + +<p><code><relative-path></code> 可以是多层的,经常是相对于alias的位置。最常见的相对路径是 "modules" 并常常被XUL Runner and Firefox使用. Code modules 是简单的js文件以 .js or .jsm 作为后缀。</p> + +<p><code><alias></code> 对于你的插件必须是唯一的,因为应用和其他的扩展共享同样的命名空间对所有的别称。</p> + +<h3 id="使用chrome.manifest">使用chrome.manifest</h3> + +<p>The easiest way for extensions and XUL applications to add custom aliases is by registering an alias in the <a href="/en/Chrome_Registration" title="en/Chrome_Registration">chrome manifest</a> using a line like this:</p> + +<pre class="eval notranslate">resource <em>aliasname</em> <em>uri/to/files/</em> +</pre> + +<p>For example, if the XPI for your <em>foo</em> extension includes a top-level modules/ directory containing the <em>bar.js</em> module (that is, the modules/ directory is a sibling to chrome.manifest and install.rdf), you could create an alias to that directory via the instruction:</p> + +<pre class="eval notranslate">resource foo modules/ +</pre> + +<p>(Don't forget the trailing slash!) You could then import the module into your JavaScript code via the statement:</p> + +<pre class="brush: js notranslate">Components.utils.import("resource://foo/bar.js"); +</pre> + +<h4 id="Programmatically_adding_aliases">Programmatically adding aliases</h4> + +<p>Custom aliases to paths that can be represented as an {{ interface("nsILocalFile") }} can be programmatically added as well. For example:</p> + +<pre class="brush: js notranslate">// Import Services.jsm unless in a scope where it's already been imported +Components.utils.import("resource://gre/Services.jsm"); + +var resProt = Services.io.getProtocolHandler("resource") + .QueryInterface(Components.interfaces.nsIResProtocolHandler); + +var aliasFile = Components.classes["@mozilla.org/file/local;1"] + .createInstance(Components.interfaces.nsILocalFile); +aliasFile.initWithPath("/some/absolute/path"); + +var aliasURI = Services.io.newFileURI(aliasFile); +resProt.setSubstitution("myalias", aliasURI); + +// assuming the code modules are in the alias folder itself +</pre> + +<h2 id="Notes">Notes</h2> + +<h3 id="自定义_modules_和_XPCOM_components">自定义 modules 和 XPCOM components</h3> + +<p>Note that prior to {{ Gecko("2.0") }} JavaScript XPCOM components are loaded before chrome registration. This means you can't use <code><a href="/en/Components.utils.import" title="en/Components.utils.import">Components.utils.import()</a></code> with your own resource URL at the top level in a component source. A possible solution is moving the call to <code><a href="/en/Components.utils.import" title="en/Components.utils.import">Components.utils.import()</a></code> into the XPCOM component constructor (<a class="external" href="http://groups.google.com/group/mozilla.dev.apps.firefox/browse_thread/thread/e178d41afa2ccc87?hl=en#" title="http://groups.google.com/group/mozilla.dev.apps.firefox/browse_thread/thread/e178d41afa2ccc87?hl=en#">discussion</a>).</p> + +<h3 id="Packaging_notes">Packaging notes</h3> + +<p>It's important to note that you should not typically put your JavaScript code modules in a JAR file in your add-on. Firefox 3.6 doesn't support them at all, and there's only one case in which it's remotely useful: a Firefox 4-only add-on which must be installed unpacked. Otherwise placing code modules in a JAR file breaks compatibility unnecessarily.</p> + +<h2 id="Importing_CommonJS_modules">Importing CommonJS modules</h2> + +<p>The JavaScript code modules described here are not the same thing as <a href="http://www.commonjs.org/specs/modules/1.0/">CommonJS modules</a>, but you can import CommonJS modules into any scope where you can use <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Language_Bindings/Components.utils.import">Components.utils.import</a>. Just call the following:</p> + +<pre class="brush: js line-numbers language-js notranslate"><code class="language-js"><span class="keyword token">const</span> <span class="punctuation token">{</span> require <span class="punctuation token">}</span> <span class="operator token">=</span> Cu<span class="punctuation token">.</span><span class="keyword token">import</span><span class="punctuation token">(</span><span class="string token">"resource://gre/modules/commonjs/toolkit/require.js"</span><span class="punctuation token">,</span> <span class="punctuation token">{</span><span class="punctuation token">}</span><span class="punctuation token">)</span></code></pre> + +<p>This will import <code>require()</code> into your scope.</p> + +<p>You can then use that to import CommonJS modules. You can import <a href="/en-US/docs/Mozilla/Add-ons/SDK">Add-on SDK</a> modules in just the same way you could from an SDK add-on:</p> + +<pre class="brush: js notranslate">// import the SDK's base64 module + +var base64 = require("sdk/base64"); +base64.encode("hello"); // "aGVsbG8="</pre> + +<p>You can import other CommonJS modules, too, as long as you know the path to them:</p> + +<pre class="brush: js notranslate">// import my module + +var myModule = require("resource://path/to/my/module.js");</pre> + +<p>In this case, though, you might be better off <a href="/en-US/Add-ons/SDK/Low-Level_APIs/_loader">creating your own loader</a>, so you can specify the <code><a href="/en-US/Add-ons/SDK/Low-Level_APIs/_loader#paths">paths</a></code> property yourself.</p> + +<h2 id="See_also" name="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Mozilla/JavaScript_code_modules">JavaScript code modules</a> topic page</li> +</ul> |