Typescript与Polymer的结合

5

我知道这个主题已经有其他问题了,但是没有一个答案特别有帮助,有些已经过时了,所以我想再次询问。

有人成功地使Polymer和Typescript配合使用吗?看起来很接近了,理想情况下我们想要向Polymer提供一个类实例或原型,然后它会处理剩下的事情。

例如,给定以下内容:

<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());

然后我们成功输出了 "name",但是点击按钮没有调用函数。

但是如果我们这样做:

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

当我们点击按钮时,会得到控制台输出,但该变量未定义。有人知道如何让它们正常工作吗?
2个回答

2

PolymerTS对于使用TypeScript开发Polymer非常有帮助。我还编写了一个Yeoman生成器generator-polymerts,以便更轻松地使用它。 - bsorrentino

1
默认字段值在构造函数中设置,但是当您将原型传递给Polymer()时,它无法访问构造函数。
相反,在created回调中设置默认值。这有点像黑客技巧,但不仅限于Typescript,我在编写用作聚合元素的闭包编译器样式类时也遇到了同样的问题。
class MyElement {
    name : string;
    created() {
      this.name = "Mike";
    }
    setFocus() {
        console.log("called");        
    }
}
Polymer(MyElement.prototype);

你如何访问“this.”变量,例如“this.$.el”等? - mikeysee
取消之前的,你可以这样做:class MyPolymerElement { $: any; }class MyElement extends MyPolymerElement {} - mikeysee
我们使用Closure Compiler为Polymer元素定义了一个扩展HTMLElement的基类。我认为你可以通过这个.externs.js文件相对简单地生成一个.d.ts文件(也许可以自动化完成):https://github.com/Polymer/polymer/blob/master/polymer.externs.js - Peter Burns

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接