2015-12-01 159 views
0

custom elements一页,我看到来扩展你的元素:在引导后扩展HTML元素

var XFooButtonPrototype = Object.create(HTMLButtonElement.prototype); 
XFooButtonPrototype.createdCallback = function() { 
    this.textContent = "I'm an x-foo button!"; 
}; 

var XFooButton = document.registerElement('x-foo-button', { 
    prototype: XFooButtonPrototype, 
    extends: 'button' 
}); 

然后它说,你可以写:让一个元素:

<x-foo></x-foo> 

或者:

<button is="x-foo-button"></button> 

问题:

  • 为什么很重要,指定extends: 'button'当元素为HTMLButtonElement obviously_继承(因为它在它的原型链HTMLButtonElement.prototype

  • 如何buttonx-foo-button之间的联系建立?由于extends: 'button'x-foo-button成为is="x-foo-button"按钮的可能选项吗?可以说“内部”会发生什么?

  • 为什么要选<button is="x-foo-button"></button>超过<x-foo></x-foo> ......?

[附录]

聚合物救我们脱离这种重复:

MyInput = Polymer({ 
    is: 'my-input', 
    extends: 'input', 
    created: function() { 
    this.style.border = '1px solid red'; 
    } 
}); 

如果extends是存在的,聚合物就会把正确的原型链与Object.getPrototypeOf(document.createElement(tag));。 所以,配套问题:

  • 为什么重复在第一?如果有extends,浏览器不应该自动执行此操作吗?
+0

我不认为双方你提到的语法是可以互换的。在_using一个自定义element_节wiki下指出: _如果您已经使用扩展来创建自 现有DOM元素(例如HTMLElement以外的其他元素)派生的自定义元素,请使用is syntax_ – Abhinav

+0

Ta发布答案。感谢百万的评论! – Merc

回答

2

您完全误解了Web组件的工作原理。

创建简单的元素

首先,你这是怎么注册一个新的元素:

var XFoo = document.registerElement('x-foo', { 
    prototype: Object.create(HTMLElement.prototype) 
}); 

要创建你可以做的其中一个元素:

<x-foo></x-foo> 

var xFoo = new XFoo(); 
document.body.appendChild(xFoo); 

var xFoo = document.createElement('x-foo') 
document.body.appendChild(xFoo); 

创建扩展元素

这是如何扩展现有元素的:

var XFooButton = document.registerElement('x-foo-button', { 
    prototype: Object.create(HTMLButtonElement.prototype), 
    extends: 'button' 
}); 

要创建一个可以执行下列操作之一:

<button is="x-foo-button"></button> 

var xFooButton = new XFooButton(); 
document.body.appendChild(xFoo); 

var xFooButton = document.createElement('button', 'x-foo-button'); 
document.body.appendChild(xFooButton); 

注意,在扩展自定义元素的情况下,注册时他们,你必须同时指定原型(设置为HTMLButtonElement.prototype,而不是HTMLElement.prototype ),扩展标签的名称(extends: 'button')。

此外,当您使用标记或createElement()创建扩展元素,你还需要指定基本元素(button)和扩展的一个(x-foo-button),

(注:我知道,我回答自己)

+0

也许“is”语法将被弃用 – Supersharp

+1

谁说的?哪里? – Merc

+0

我听说他们正在尝试提出比“is”语法更好的东西,但目前为止还没有。 – MarcG

0

我认为它Importent这里要说:

警告不推荐使用浏览器的API方法 在这里,在这个问题上.registerElement是用它得到了由.defineElement更换API有改变

电流的方式来定义一个元素

class AppDrawer extends HTMLElement { 
 
    constructor() { 
 
    super() 
 
    this.innerHTML = '<h1>UH</h1>'  
 
    } 
 
} 
 

 
window.customElements.define('app-drawer', AppDrawer); 
 

 
// Or use an anonymous class if you don't want a named constructor in current scope. 
 

 
window.customElements.define('app-drawer-noname', class extends HTMLElement { 
 
    constructor() { 
 
    super() 
 
    this.innerHTML = '<h1>UH AH</h1>'  
 
    } 
 
});
Example - defining a mobile drawer panel, < app - drawer >: 
 
Example usage: 
 
<app-drawer></app-drawer> 
 
<app-drawer-noname></app-drawer-noname>

```