带有聚合物的打字稿

时间:2014-10-21 05:29:59

标签: typescript polymer

我知道关于这个主题还有其他问题,但没有一个答案特别有用,有些已经过时,所以我想我会再问一次。

有没有人有幸让Polymer和Typescript发挥得很好?看起来它几乎就在那里,理想情况下我们想要为聚合物提供一个类实例或原型,然后它会处理剩下的事情。

例如,给出以下内容:

<link rel="import" href="../bower_components/polymer/polymer.html">

<polymer-element name="my-element" attributes="color">
    <template>       
        Hello there <strong>{{name}}</strong>
        <button on-click="{{setFocus}}">Set focus to text input</button>
    </template>
    <script src="my-element.js"></script>    
</polymer-element>

如果我们这样做:

class MyElement {
    name = "Mike";
    setFocus() {
        console.log("called");        
    }
}
Polymer(new MyElement());

然后我们得到&#34; name&#34;输出正确但单击按钮不会调用该功能。

但是,如果我们这样做:

class MyElement {
    name = "Mike";
    setFocus() {
        console.log("called");        
    }
}
Polymer(MyElement.prototype);

然后我们在单击按钮时获得控制台输出,但变量未定义。

任何人都知道我们如何让这些玩得很好?

2 个答案:

答案 0 :(得分:2)

我写了一个库来处理这个,检查https://github.com/nippur72/PolymerTS,但只适用于新的Polymer(&gt; = 1.0)。

答案 1 :(得分:1)

默认字段值在构造函数中设置,但是当您将原型传递给Polymer()时,它无权访问构造函数。

而是在created回调中设置默认值。这有点像黑客,但它并不仅限于Typescript,我遇到了编写闭包编译器样式类用作聚合物元素的相同事情。

class MyElement {
    name : string;
    created() {
      this.name = "Mike";
    }
    setFocus() {
        console.log("called");        
    }
}
Polymer(MyElement.prototype);