Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript with Polymer

I know that there have been other questions on this topic but none of the answers have been particularly helpful and some are out of date so I thought I would ask again.

Has anyone had any luck with getting Polymer and Typescript to play nice? It seems like its very almost there, ideally we want to supply a class instance or prototype to polymer then it takes care of the rest.

For example given the following:

<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>

If we do this:

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

Then we get "name" outputted correctly but clicking the button does not call the function.

However if we do this:

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

Then we get the console output when we click the button but the variable is undefined.

Anyone have any clue how we get these to play nice?

like image 927
mikeysee Avatar asked Oct 19 '22 23:10

mikeysee


2 Answers

I wrote a library to handle just this, check https://github.com/nippur72/PolymerTS, but works only with the new Polymer (>=1.0 that is).

like image 165
nino.porcino Avatar answered Oct 23 '22 22:10

nino.porcino


Default field values are set in the constructor, but when you pass the prototype to Polymer() it doesn't have access to the constructor.

Instead, set default values in the created callback. It's a bit of a hack, but it's not limited to just Typescript, I've run into the same thing writing closure-compiler style classes for use as polymer elements.

class MyElement {
    name : string;
    created() {
      this.name = "Mike";
    }
    setFocus() {
        console.log("called");        
    }
}
Polymer(MyElement.prototype);
like image 32
Peter Burns Avatar answered Oct 23 '22 22:10

Peter Burns