【发布时间】:2016-07-27 18:20:51
【问题描述】:
我想在本地开发一些 web 组件,即使互操作性不是很好。因此,我在我的 ubuntu OS 的 chrome://flags 选项卡下启用了 google-chrome-stable 版本 50.0.2661.102 中的实验性网络平台功能......但我仍然只有不推荐使用的(根据link to developer.mozilla docs )方法:
document.registerElement( {...})
在 Firefox 中也是如此。我知道如果我安装了聚合物,polyfills 会修复它,但据我所知,聚合物 api 与 W3C 标准并非 100% 相同。有没有人设法在具有最新标准的浏览器中本地尝试 Web 组件?尤其是我想尝试的标准的这一部分:
2.1.1 Creating an autonomous custom element
This section is non-normative.
For the purposes of illustrating how to create an autonomous custom element, let's define a custom element that encapsulates rendering a small icon for a country flag. Our goal is to be able to use it like so:
<flag-icon country="nl"></flag-icon>
To do this, we first declare a class for the custom element, extending HTMLElement:
class FlagIcon extends HTMLElement {
constructor() {
super();
this._countryCode = null;
}
static get observedAttributes() { return ["country"]; }
attributeChangedCallback(name, oldValue, newValue) {
// name will always be "country" due to observedAttributes
this._countryCode = newValue;
this._updateRendering();
}
connectedCallback() {
this._updateRendering();
}
get country() {
return this._countryCode;
}
set country(v) {
this.setAttribute("country", v);
}
_updateRendering() {
// Left as an exercise for the reader. But, you'll probably want to
// check this.ownerDocument.defaultView to see if we've been
// inserted into a document with a browsing context, and avoid
// doing any work if not.
}
}
We then need to use this class to define the element:
customElements.define("flag-icon", FlagIcon);
At this point, our above code will work! The parser, whenever it sees the flag-icon tag, will construct a new instance of our FlagIcon class, and tell our code about its new country attribute, which we then use to set the element's internal state and update its rendering (when appropriate).
You can also create flag-icon elements using the DOM API:
const flagIcon = document.createElement("flag-icon")
flagIcon.country = "jp"
document.body.appendChild(flagIcon)
Finally, we can also use the custom element constructor itself. That is, the above code is equivalent to:
const flagIcon = new FlagIcon()
flagIcon.country = "jp"
document.body.appendChild(flagIcon)
我想我也会尝试在 ubuntu 上安装 google-chrome-unstable,它可能内置了 API。
谢谢
更新:即使是 Google Chrome 53.0.2785.30 dev (google-chrome-unstable on ubuntu) /w 标志设置,甚至没有实现标准。
【问题讨论】:
标签: javascript google-chrome cross-browser web-component custom-element