我的web组件(Polymer1.0)改变了轻量级DOM,并尝试将单击转换为自定义事件。
<link rel="import" href="path/to/polymer.html">
<dom-module id="x-custom">
<template>
<content></content>
<!-- used this way <x-custom><div></div></x-custom> -->
</template>
<script>
(function() {
function init() {
var myRoot = Polymer.dom(this);
var firstDiv = myRoot.querySelectorAll("div")[0];
var itemDiv = document.createElement("div");
itemDiv.textContent = "Yadda";
firstDiv.appendChild(itemDiv);
itemDiv.addEventListener("click", follow);
}
function follow()
{
console.log("follow");
Polymer.fire("custom-event");
}
Polymer({
is: 'x-custom',
ready: init
});
})();
</script>
</dom-module>它告诉我聚合物没有功能火。调用此方法的正确方法是什么?可能这里也有反模式.
发布于 2015-07-30 13:55:20
聚合物对象内部没有fire方法。fire方法在Polymer.Base中,但是除非您声明一个原型,否则不能直接使用它,因此需要this。您可以通过打开Dev工具并键入Polymer和一个点来查看所有的聚合物特性和方法。
总之,您应该使用this.fire。
<dom-module id="x-custom">
<template>
<content></content>
<!-- used this way <x-custom><div></div></x-custom> -->
</template>
<script>
(function() {
function init() {
var myRoot = Polymer.dom(this);
var firstDiv = myRoot.querySelectorAll("div")[0];
var itemDiv = document.createElement("div");
itemDiv.textContent = "Yadda";
firstDiv.appendChild(itemDiv);
itemDiv.addEventListener("click", follow.bind(this)); // notice the .bind here
}
function follow()
{
console.log("follow");
this.fire("custom-event");
}
Polymer({
is: 'x-custom',
ready: init
});
})();
</script>
</dom-module>发布于 2015-07-30 11:42:11
您需要将您的函数放入主Polymer()函数中。它抛出错误,因为Polymer()函数不在init()函数的范围内。您还需要在Polymer()函数中声明在模板中使用的所有自定义属性。
如下所示:
<link rel="import" href="path/to/polymer.html">
<dom-module id="x-custom">
<template>
<content></content>
<!-- used this way <x-custom><div></div></x-custom> -->
</template>
<script>
(function() {
Polymer({
is: 'x-custom',
properties: {
customProperty1: {
type: String
},
customProperty2: {
type: String
}
},
ready: function() {
var myRoot = Polymer.dom(this);
var firstDiv = myRoot.querySelectorAll("div")[0];
var itemDiv = document.createElement("div");
itemDiv.textContent = "Yadda";
firstDiv.appendChild(itemDiv);
itemDiv.addEventListener("click", follow);
},
follow: function() {
console.log("follow");
Polymer.fire("custom-event");
}
});
})();
</script>
</dom-module>https://stackoverflow.com/questions/31721420
复制相似问题