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. ThefactoryImpl
method is not called if the element is created from markup by the HTML parser, or if the element is created usingdocument.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标签(例如,input
或 button
,而不是扩展其他自定义标签,这将在以后的版本中支持)。这些原生标签扩展被称为扩展自定义标签类。
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 ofcreatedCallback
-
attached
instead ofattachedCallback
-
detached
instead ofdetachedCallback
-
attributeChanged
instead ofattributeChangedCallback
-
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:
标签基本初始化顺序是:
-
created
callback - local DOM initialized
-
ready
callback factoryImpl
callback-
attached
callback
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 beforeready
.The
ready
callback is always called beforeattached
.-
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 becomeready
in any order.
这意味着元素的子DOM可能在父标签之前或之后初始化,和一个标签的兄弟姐妹可能会以任何顺序ready
** 。
For accessing sibling elements when an element initializes, you can callasync
from inside theattached
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
。