3-2 Registration and lifecycle 注冊和生命周期

layout: default
type: guide
shortname: Docs
title: Registration and lifecycle
subtitle: Developer guide

{% include toc.html %}

Register a custom element {#register-element}

注冊一個自定義標(biāo)簽{#register-element}

To register a custom element, use the Polymer function, and pass in the prototype for the new element. The prototype must have an is property that specifies the HTML tag name for your custom element.
要注冊一個自定義標(biāo)簽,使用Polymer函數(shù),并通過新標(biāo)簽的原型注冊。原型必須有一個is屬性來為你的自定義標(biāo)簽指定HTML標(biāo)簽名。

By specification, the custom element's name must contain a dash (-).
為了規(guī)范,自定義標(biāo)簽必須包含一個破折號(-)

Example:
例:

// register an element 注冊一個標(biāo)簽
MyElement = Polymer({

  is: 'my-element',

  // See below for lifecycle callbacks 請參閱下面的生命周期回調(diào)函數(shù)
  created: function() {
    this.textContent = 'My element!';
  }

});

// create an instance with createElement: 
// 使用createElement創(chuàng)建一個實例:
var el1 = document.createElement('my-element');

// ... or with the constructor: 或者使用構(gòu)造函數(shù):
var el2 = new MyElement();

The Polymer function registers the element with the browser and returns a constructor that can be used to create new instances of your element via code.
Polymer函數(shù)注冊瀏覽器標(biāo)簽并返回一個可以通過代碼創(chuàng)建新實例的構(gòu)造函數(shù)。
The Polymer function sets up the prototype chain for your custom element, chaining it to the {{site.project_title}} Base prototype (which provides {{site.project_title}} value-added features), so you cannot set up your own prototype chain. However, you can use behaviors to share code between elements.
Polymer函數(shù)為你的自定義標(biāo)簽設(shè)置了原型鏈,它鏈接到Polymer Base原型(提供Polymer value-added功能),所以你不能建立自己的原型鏈。但是,您可以使用行為在元素之間共享代碼。

Define a custom constructor {#custom-constructor}

定義一個自定義構(gòu)造函數(shù){#custom-constructor}

The Polymer method returns a basic constructor that can be used to instantiate the custom element. If you want to pass arguments to the constructor to configure the new element, you can specify a custom factoryImpl function on the prototype.
Polymer方法返回可用于實例化自定義標(biāo)簽的一個基本構(gòu)造函數(shù)。如果你想傳遞參數(shù)到構(gòu)造函數(shù)來配置新的標(biāo)簽,你可以在原型上指定一個自定義factoryImpl函數(shù)。
The constructor returned from Polymer creates an instance using
document.createElement, then invokes the user-supplied factoryImpl function with this bound to the element instance. Any arguments passed to the actual constructor are passed on to the factoryImpl function.
該構(gòu)造函數(shù)通過Polymer使用document.createElement創(chuàng)建一個實例而返回。然后調(diào)用用戶提供的factoryImpl 函數(shù)與this綁定到標(biāo)簽實例。任何參數(shù)都通過factoryImpl 函數(shù)傳遞到實際構(gòu)造函數(shù)。
Example:

MyElement = Polymer({

  is: 'my-element',

  factoryImpl: function(foo, bar) {
    this.foo = foo;
    this.configureWithBar(bar);
  },

  configureWithBar: function(bar) {
    ...
  }

});

var el = new MyElement(42, 'octopus');

Two notes about the custom constructor:
關(guān)于自定義構(gòu)造函數(shù)有兩點要注意:

  • The factoryImpl method is only invoked when you create an element using the constructor. The factoryImpl method is not called if the element is created from markup by the HTML parser, or if the element is created using document.createElement.
  • factoryImpl方法只有當(dāng)你使用構(gòu)造函數(shù)創(chuàng)建標(biāo)簽時才能被調(diào)用。如果從HTML解析器標(biāo)記或者使用document.createElement創(chuàng)建標(biāo)簽,factoryImpl方法不會被調(diào)用。
  • The factoryImpl method is called after the element is initialized (local DOM created, default values set, and so on). See Ready callback and element initialization for more information.
  • 標(biāo)簽初始化后factoryImpl方法被調(diào)用(局部DOM已創(chuàng)建、默認(rèn)值設(shè)定、等等)。更多信息參看準(zhǔn)備回調(diào)和標(biāo)簽初始化

Extend native HTML elements {#type-extension}

擴展原生HTML標(biāo)簽 {#type-extension}

Polymer currently only supports extending native HTML elements (for example, input, or button, as opposed to extending other custom elements, which will be supported in a future release). These native element extensions are called type extension custom elements.
Polymer目前只支持?jǐn)U展原生HTML標(biāo)簽(例如,inputbutton,而不是擴展其他自定義標(biāo)簽,這將在以后的版本中支持)。這些原生標(biāo)簽擴展被稱為擴展自定義標(biāo)簽類
To extend a native HTML element, set the extends property on your prototype to the tag name of the element to extend.
要擴展原生HTML標(biāo)簽,在你的原型設(shè)置extends屬性為原生標(biāo)簽名稱來擴展。

Example:

MyInput = Polymer({

  is: 'my-input',

  extends: 'input',

  created: function() {
    this.style.border = '1px solid red';
  }

});

var el1 = new MyInput();
console.log(el1 instanceof HTMLInputElement); // true

var el2 = document.createElement('input', 'my-input');
console.log(el2 instanceof HTMLInputElement); // true

To use a type-extension element in markup, use the native tag and add an is attribute that specifies the extension type name:
要在標(biāo)記中使用擴展標(biāo)簽類型,使用原生標(biāo)簽,并添加一個is屬性指定擴展類型名稱:

<input is="my-input">


<a id="basic-callbacks"></a>

Define an element in the main HTML document {#main-document-definitions}

在主HTML文檔中定義一個標(biāo)簽{#main-document-definitions}

Note: You should only define elements from the main document when experimenting. In production, elements should always be defined in separate files and imported into your main document.
{: .alert .alert-info }
注: 你只應(yīng)該在實驗時在主文檔定義標(biāo)簽,在生產(chǎn)時,標(biāo)簽應(yīng)始終在單獨的文件中定義并導(dǎo)入到主文檔中。
To define an element in your main HTML document, define the element from HTMLImports.whenReady(callback). callback is invoked when all imports in the document have finished loading.
要定義一個標(biāo)簽到你的主HTML文檔,定義標(biāo)簽從HTMLImports.whenReady(callback),當(dāng)所有imports加載完成后callback被調(diào)用。

<!DOCTYPE html>
<html>
  <head>
    <script src="bower_components/webcomponentsjs/webcomponents-lite.js">
    </script>
    <link rel="import" href="bower_components/polymer/polymer.html">
    <title>Defining a Polymer Element from the Main Document</title>
  </head>
  <body>
    <dom-module id="main-document-element">
      <template>
        <p>
          Hi! I'm a Polymer element that was defined in the
          main document!
        </p>
      </template>
      <script>
        HTMLImports.whenReady(function () {
          Polymer({
            is: 'main-document-element'
          });
        });
      </script>
    </dom-module>
    <main-document-element></main-document-element>
  </body>
</html>

Lifecycle callbacks {#lifecycle-callbacks}

生命周期回調(diào)函數(shù) {#lifecycle-callbacks}

Polymer's Base prototype implements the standard Custom Element lifecycle callbacks to perform tasks necessary for Polymer's built-in features. The hooks in turn call shorter-named lifecycle methods on your prototype.
Polymer的基本原型實現(xiàn)了用標(biāo)準(zhǔn)的自定義標(biāo)簽生命周期回調(diào)函數(shù)進行必要的Polymer內(nèi)置功能的任務(wù)。鉤子又呼叫原型中的短命名生命周期方法。

  • created instead of createdCallback
  • attached instead of attachedCallback
  • detached instead of detachedCallback
  • attributeChanged instead of attributeChangedCallback
  • created 替換為 createdCallback // 已創(chuàng)建
  • attached 替換為 attachedCallback // 已連接
  • detached 替換為 detachedCallback // 已分離
  • attributeChanged 替換為 attributeChangedCallback//特征已改變

You can fallback to using the low-level methods if you prefer (in other words, you can simply implement createdCallback in your prototype).
您可以還原到使用低級別的方法,如果你喜歡(換句話說,你可以簡單地實現(xiàn)createdCallback在你的原型)。
Polymer adds an extra callback, ready, which is invoked when Polymer has finished creating and initializing the element's local DOM.
Polymer增加了一個額外的回調(diào), ready,它被調(diào)用時,Polymer已完成創(chuàng)建和初始化標(biāo)簽的局部DOM。

Example:

MyElement = Polymer({

  is: 'my-element',

  created: function() {
    console.log(this.localName + '#' + this.id + ' was created');
  },

  attached: function() {
    console.log(this.localName + '#' + this.id + ' was attached');
  },

  detached: function() {
    console.log(this.localName + '#' + this.id + ' was detached');
  },

  attributeChanged: function(name, type) {
    console.log(this.localName + '#' + this.id + ' attribute ' + name +
      ' was changed to ' + this.getAttribute(name));
  }

});

Ready callback and local DOM initialization {#ready-method}

Ready回調(diào)函數(shù)和局部DOM初始化{#ready-method}

The ready callback is called when an element's local DOM is ready.
It is called after the element's template has been stamped and all elements inside the element's local DOM have been configured (with values bound from parents, deserialized attributes, or else default values) and had their ready method called.
當(dāng)一個標(biāo)簽到局部DOM已經(jīng)準(zhǔn)備好時ready回調(diào)函數(shù)被調(diào)用。它在標(biāo)簽?zāi)0逋瓿纱蛴『退袠?biāo)簽內(nèi)的局部DOM配置完成后被調(diào)用(從父元素值綁定,反序列化特征,或者其它默認(rèn)值)
Implement ready when it's necessary to manipulate an element's local DOM when the element is constructed.
當(dāng)標(biāo)簽已經(jīng)被構(gòu)造好必須操作標(biāo)簽的局部DOM時來執(zhí)行ready函數(shù)

ready: function() {
  // access a local DOM element by ID using this.$
  this.$.header.textContent = 'Hello!';
}

Note: This example uses Automatic node finding to access a local DOM element.
{: .alert .alert-info }
注:這個示例使用自動尋找節(jié)點node來訪問一個局部DOM標(biāo)簽。
Within a given tree, ready is generally called in document order, but you should not rely on the ordering of initialization callbacks between sibling elements, or between a host element and its light DOM children.
在給定的樹上,ready 通常按文檔順序回調(diào),但是你不應(yīng)當(dāng)在兄弟標(biāo)簽之間,或者在主元素和它的子DOM依賴初始化回調(diào)順序.

Initialization order {#initialization-order}

初始化順序

The element's basic initialization order is:
標(biāo)簽基本初始化順序是:

Note that the initialization order may vary depending on whether or not the browser includes native support for web components. In particular, there are no guarantees with regard to initialization timing between sibling elements or between parents and light DOM children. You should not rely on observed timing to be identical across browsers, except as noted below.
請注意,根據(jù)瀏覽器是否包含Web組件的原生支持初始化順序可能會有所不同 。 特別是有關(guān)于初始化時序同級元素之間或父與子DOM之間沒有保證。 你不應(yīng)該依賴于不同的瀏覽器觀測到的時間是相同的,除了如下所述。
For a given element:
對于給定的元件:

  • The created callback is always called before ready.

  • The ready callback is always called before attached.

  • The ready callback is called on any local DOM children before it's called on the host element. ready回調(diào)函數(shù)已被調(diào),任何局部DOM在主標(biāo)簽調(diào)用之前
    This means that an element's light DOM children may be initialized before or after the parent element, and an element's siblings may become ready in any order.
    這意味著元素的子DOM可能在父標(biāo)簽之前或之后初始化,和一個標(biāo)簽的兄弟姐妹可能會以任何順序ready** 。
    For accessing sibling elements when an element initializes, you can call async from inside the attached callback:
    為了訪問兄弟元素,當(dāng)一個元素初始化,您可以撥打async從內(nèi)部attached回調(diào):

    attached: function() {
    this.async(function() {
    // access sibling or parent elements here
    });
    }

Registration callback

注冊回調(diào)

Polymer.Base also implements registerCallback, which is called by Polymer() to allow Polymer.Base to supply a layering system for Polymer features.
Polymer.Base還實現(xiàn)了registerCallback,這被稱為由Polymer()
允許Polymer.Base提供一個分層系統(tǒng)用于Polymer功能。

Static attributes on host {#host-attributes}

主機靜態(tài)屬性 {#host-attributes}

If a custom element needs HTML attributes set on it at create-time, the attributes may be declared in a hostAttributes property on the prototype, where keys are the attribute names and values are the values to be assigned. Values should typically be provided as strings, as HTML attributes can only be strings; however, the standard serialize method is used to convert values to strings,
so true will serialize to an empty attribute, and false will result in no attribute set, and so forth (see Attribute serialization for more
details).
如果自定義元素需要HTML屬性設(shè)置就可以了,在創(chuàng)建時,該屬性可以在聲明hostAttributes的原型,其中鍵是屬性名稱和值是值分配財產(chǎn)。 值通常應(yīng)作為字符串,如HTML屬性只能是字符串; 然而,標(biāo)準(zhǔn)的serialize方法被用于將值轉(zhuǎn)換為字符串,所以true將序列化為一個空的屬性, false將導(dǎo)致沒有屬性集,等等(見屬性序列化的更多細(xì)節(jié))。

Example:

<script>

  Polymer({

    is: 'x-custom',

    hostAttributes: {
      'string-attribute': 'Value',
      'boolean-attribute': true
      tabindex: 0
    }

  });

</script>

Results in:

<x-custom string-attribute="Value" boolean-attribute tabindex="0"></x-custom>

Note: The class attribute can't be configured using hostAttributes.
{: .alert .alert-error }
注: class屬性不能使用配置hostAttributes

Behaviors {#prototype-mixins}

行為{#prototype-mixins}

Elements can share code in the form of behaviors, which can define properties, lifecycle callbacks, event listeners, and other features.
標(biāo)簽?zāi)茉?em>behaviors上共享代碼,它可以定義屬性,生命周期回調(diào)函數(shù),事件監(jiān)聽,和其它功能。

For more information, see Behaviors.
更多信息,參看行為

Class-style constructor {#element-constructor}

構(gòu)造類樣式 {#element-constructor}

If you want to set up your custom element's prototype chain but not register it immediately, you can use the Polymer.Class function. Polymer.Class takes the same prototype argument as the Polymer function, and sets up the prototype chain, but does not register the element. Instead it returns a constructor that can be passed to document.registerElement to register your element with the browser, and after which can be used to instantiate new instances of your element via code.
如果你想設(shè)置你的自定義標(biāo)簽原型鏈但立即注冊,你可以使用Polymer.Class函數(shù)。Polymer.Class使用與Polymer函數(shù)相同的原型參數(shù)設(shè)置原型鏈但注冊標(biāo)簽。相反,它返回一個能夠通過document.registerElement在瀏覽器中注冊你的標(biāo)簽的構(gòu)造函數(shù),這個構(gòu)造函數(shù)以后可以用來通過代碼實例化新實例。
If you want to define and register the custom element in one step, use the Polymer function.
如果你想一步到位同時定義和注冊自定義標(biāo)簽,使用 Polymer 函數(shù).
Example:

var MyElement = Polymer.Class({

  is: 'my-element',

  // See below for lifecycle callbacks
  created: function() {
    this.textContent = 'My element!';
  }

});

document.registerElement('my-element', MyElement);

// Equivalent:
var el1 = new MyElement();
var el2 = document.createElement('my-element');

Polymer.Class is designed to provide similar ergonomics to a speculative future where an ES6 class may be defined and provided to document.registerElement.
Polymer.Class旨在提供類似的人體工程學(xué)設(shè)計來推測未來ES6類可能定義和提供給document.registerElement

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容