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}

注册一个自定义标签{#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.
要注册一个自定义标签,使用Polymer函数,并通过新标签的原型注册。原型必须有一个is属性来为你的自定义标签指定HTML标签名。

By specification, the custom element's name must contain a dash (-).
为了规范,自定义标签必须包含一个破折号(-)

Example:
例:

// register an element 注册一个标签
MyElement = Polymer({

  is: 'my-element',

  // See below for lifecycle callbacks 请参阅下面的生命周期回调函数
  created: function() {
    this.textContent = 'My element!';
  }

});

// create an instance with createElement: 
// 使用createElement创建一个实例:
var el1 = document.createElement('my-element');

// ... or with the constructor: 或者使用构造函数:
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函数注册浏览器标签并返回一个可以通过代码创建新实例的构造函数。
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函数为你的自定义标签设置了原型链,它链接到Polymer Base原型(提供Polymer value-added功能),所以你不能建立自己的原型链。但是,您可以使用行为在元素之间共享代码。

Define a custom constructor {#custom-constructor}

定义一个自定义构造函数{#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方法返回可用于实例化自定义标签的一个基本构造函数。如果你想传递参数到构造函数来配置新的标签,你可以在原型上指定一个自定义factoryImpl函数。
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.
该构造函数通过Polymer使用document.createElement创建一个实例而返回。然后调用用户提供的factoryImpl 函数与this绑定到标签实例。任何参数都通过factoryImpl 函数传递到实际构造函数。
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:
关于自定义构造函数有两点要注意:

  • 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方法只有当你使用构造函数创建标签时才能被调用。如果从HTML解析器标记或者使用document.createElement创建标签,factoryImpl方法不会被调用。
  • 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.
  • 标签初始化后factoryImpl方法被调用(局部DOM已创建、默认值设定、等等)。更多信息参看准备回调和标签初始化

Extend native HTML elements {#type-extension}

扩展原生HTML标签 {#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目前只支持扩展原生HTML标签(例如,inputbutton,而不是扩展其他自定义标签,这将在以后的版本中支持)。这些原生标签扩展被称为扩展自定义标签类
To extend a native HTML element, set the extends property on your prototype to the tag name of the element to extend.
要扩展原生HTML标签,在你的原型设置extends属性为原生标签名称来扩展。

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:
要在标记中使用扩展标签类型,使用原生标签,并添加一个is属性指定扩展类型名称:

<input is="my-input">


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

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

在主HTML文档中定义一个标签{#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 }
注: 你只应该在实验时在主文档定义标签,在生产时,标签应始终在单独的文件中定义并导入到主文档中。
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.
要定义一个标签到你的主HTML文档,定义标签从HTMLImports.whenReady(callback),当所有imports加载完成后callback被调用。

<!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}

生命周期回调函数 {#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的基本原型实现了用标准的自定义标签生命周期回调函数进行必要的Polymer内置功能的任务。钩子又呼叫原型中的短命名生命周期方法。

  • created instead of createdCallback
  • attached instead of attachedCallback
  • detached instead of detachedCallback
  • attributeChanged instead of attributeChangedCallback
  • created 替换为 createdCallback // 已创建
  • 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).
您可以还原到使用低级别的方法,如果你喜欢(换句话说,你可以简单地实现createdCallback在你的原型)。
Polymer adds an extra callback, ready, which is invoked when Polymer has finished creating and initializing the element's local DOM.
Polymer增加了一个额外的回调, ready,它被调用时,Polymer已完成创建和初始化标签的局部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回调函数和局部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.
当一个标签到局部DOM已经准备好时ready回调函数被调用。它在标签模板完成打印和所有标签内的局部DOM配置完成后被调用(从父元素值绑定,反序列化特征,或者其它默认值)
Implement ready when it's necessary to manipulate an element's local DOM when the element is constructed.
当标签已经被构造好必须操作标签的局部DOM时来执行ready函数

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 }
注:这个示例使用自动寻找节点node来访问一个局部DOM标签。
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 通常按文档顺序回调,但是你不应当在兄弟标签之间,或者在主元素和它的子DOM依赖初始化回调顺序.

Initialization order {#initialization-order}

初始化顺序

The element's basic initialization order is:
标签基本初始化顺序是:

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.
请注意,根据浏览器是否包含Web组件的原生支持初始化顺序可能会有所不同 。 特别是有关于初始化时序同级元素之间或父与子DOM之间没有保证。 你不应该依赖于不同的浏览器观测到的时间是相同的,除了如下所述。
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回调函数已被调,任何局部DOM在主标签调用之前
    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可能在父标签之前或之后初始化,和一个标签的兄弟姐妹可能会以任何顺序ready** 。
    For accessing sibling elements when an element initializes, you can call async from inside the attached callback:
    为了访问兄弟元素,当一个元素初始化,您可以拨打async从内部attached回调:

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

Registration callback

注册回调

Polymer.Base also implements registerCallback, which is called by Polymer() to allow Polymer.Base to supply a layering system for Polymer features.
Polymer.Base还实现了registerCallback,这被称为由Polymer()
允许Polymer.Base提供一个分层系统用于Polymer功能。

Static attributes on host {#host-attributes}

主机静态属性 {#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属性设置就可以了,在创建时,该属性可以在声明hostAttributes的原型,其中键是属性名称和值是值分配财产。 值通常应作为字符串,如HTML属性只能是字符串; 然而,标准的serialize方法被用于将值转换为字符串,所以true将序列化为一个空的属性, false将导致没有属性集,等等(见属性序列化的更多细节)。

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.
标签能在behaviors上共享代码,它可以定义属性,生命周期回调函数,事件监听,和其它功能。

For more information, see Behaviors.
更多信息,参看行为

Class-style constructor {#element-constructor}

构造类样式 {#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.
如果你想设置你的自定义标签原型链但立即注册,你可以使用Polymer.Class函数。Polymer.Class使用与Polymer函数相同的原型参数设置原型链但注册标签。相反,它返回一个能够通过document.registerElement在浏览器中注册你的标签的构造函数,这个构造函数以后可以用来通过代码实例化新实例。
If you want to define and register the custom element in one step, use the Polymer function.
如果你想一步到位同时定义和注册自定义标签,使用 Polymer 函数.
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旨在提供类似的人体工程学设计来推测未来ES6类可能定义和提供给document.registerElement

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,132评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,802评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,566评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,858评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,867评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,695评论 1 282
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,064评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,705评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,915评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,677评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,796评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,432评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,041评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,992评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,223评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,185评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,535评论 2 343

推荐阅读更多精彩内容