5

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?

2 Answers 2

2

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

1
  • PolymerTS is very helpful to work with Polymer using Typescript. I wrote also a Yeoman generator generator-polymerts to make easier work with it Aug 14, 2015 at 14:23
1

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);
3
  • How would you go about accessing the "this." variables such as "this.$.el" and so on?
    – mikeysee
    Oct 21, 2014 at 23:05
  • Scratch that, you can do this: class MyPolymerElement { $: any; }class MyElement extends MyPolymerElement {}
    – mikeysee
    Oct 21, 2014 at 23:07
  • What we're doing with Closure Compiler is defining a base class for polymer elements that extends HTMLElement. You could generate a .d.ts from this .externs.js in a pretty straightforwards way I think (maybe automatically?): github.com/Polymer/polymer/blob/master/polymer.externs.js Oct 22, 2014 at 23:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.