
Security News
Package Maintainers Call for Improvements to GitHub’s New npm Security Plan
Maintainers back GitHub’s npm security overhaul but raise concerns about CI/CD workflows, enterprise support, and token management.
Write Polymer 1.0 elements as TypeScript @decorated classes.
Install via bower:
bower install -save polymer-ts
You'll get the following files in bower_components/polymer-ts
:
polymer-ts.html
the html file to include via <link rel="import">
that loads PolymerTSpolymer-ts.min.html
the html file to include via <link rel="import">
that loads PolymerTS (minified version)polymer-ts.d.ts
the file to reference in your TypeScript code (/// <reference path="...">
)polymer-ts.ts
the source TypeScript file for debugging purposespolymer-ts.js
or polymer-ts.min.js
the JavaScript file if you want to include PolymerTS via <script src="">
@component(tagName)
sets component's name (equivalent to is:
in PolymerJS)@extend(name)
extends a native tag (equivalent to extends:
in PolymerJS)@hostAttributes(attrs)
sets host attributes (equivalent to hostAttributes:
in PolymerJS)@property(defs)
sets a property (equivalent to properties:
in PolymerJS)@observe(propList)
sets an observer function on single or multiple properties (equivalent to observers:
in PolymerJS)@computed()
defines a computed property@listen(eventName)
sets an event listener function (equivalent to listeners:
in PolymerJS)@behavior(className)
gets the behaviors of the class (equivalent to behaviors:
in PolymerJS)className.register()
registers in PolymerclassName.register(true)
registers in Polymer but not in document.registerElement()
className.create()
creates an instance of the elementfactoryImpl()
)Unsupported:
polymer.Base
classA class-element:
factoryImpl()
)In the head
section of your main .html file:
<head>
<!-- webcomponents, polymer standard, polymer-ts -->
<script src="bower_components/webcomponentsjs/webcomponents-lite.js"></script>
<link rel="import" href="bower_components/polymer/polymer.html">
<link rel="import" href="bower_components/polymer-ts/polymer-ts.html">
<!-- your custom elements -->
<link rel="import" href="elements/my-element.html">
<!-- your application -->
<script src="myapp.js"></script>
</head>
In your custom element (e.g. elements/my-element.html
):
<dom-module id="my-element">
<!-- ... your custom element here... -->
</dom-module>
<!-- your element code typescript transpiled file -->
<script type="text/javascript" src="my-element.js"></script>
In your element typescript code (e.g. elements/my-element.ts
):
/// <reference path="../bower_components/polymer-ts/polymer-ts.d.ts" />
@component("my-element")
class MyElement extends polymer.Base
{
}
// after the element is defined, we register it in Polymer
MyElement.register();
The above example loads in the following order:
Note: due to an issue in WebComponents,
you can't use the <script>
tag on the main page to load PolymerTS or custom elements,
you have always to use the <link rel="import">
syntax.
This will make sure that scripts will be loaded in the correct order in all browsers.
If for some reason you want to use script inclusion for your elements, you have to load
Polymer and PolymerTS via script too. Polymer doesn't have a polymer.js
file (it's shipped as .html
only),
but you can get one from greenify/polymer-js.
Any global code in your app that depends on Polymer should be started only after the event
WebComponentsReady
has been fired:
window.addEventListener('WebComponentsReady', (e) =>
{
// any code that depends on polymer here
});
New elements can be quickly scaffolded using the polymerts:el
yeoman
generator available with the package generator-polymerts.
First install yeoman
and generator-polymerts
:
npm install -g yo
npm install -g generator-polymerts
then use the polymerts:el
generator to create a new element:
yo polymerts:el my-element
Sets the tag name of the custom component. The decorator is applied on the class
keyword. Tag names must include a -
as per WebComponents specs.
Example of a <my-element>
:
@component("my-element")
class MyElement extends polymer.Base
{
}
If the component extends a native HTML tag, pass the "base" tag name as second argument (alternatively, use the @extend
decorator)
@component("my-button","button")
class MyButton extends polymer.Base
{
}
Specifies that the element is an extension of a native HTML element.
@component("my-button")
@extend("button")
class MyButton extends polymer.Base
{
}
Creates a Polymer property. It can be applied to a member field or a function. When applied to a function, the property becomes a computed property.
The parameter def
is a map object that sets the options for the property:
{
type?: any; // Boolean, Date, Number, String, Array or Object
value?: any; // default value for the property
reflectToAttribute?: boolean; // should the property reflect to attribute
readonly?: boolean; // marks property as read-only
notify?: boolean; // if set to true, will trigger "propname-changed"
computed?: string; // computed function call (as string)
observer?: string; // observer function call (as string)
}
Examples:
@property({ type: number, value: 42 })
initialValue: number;
The default value for a property is optional as long as the property is initialized:
@property()
myprop = 42; // direct initialization
or
@property({ type: number })
myprop: number;
constructor() {
this.myprop = 42; // initialized within constructor
}
While you can specify computed
and observer
in a property definition,
there are the specific decorators @computed
and @observe
that are easier to use.
Sets an observer function for a single property or a list of properties.
If observing a single property, the function must be of the type function(newVal,OldVal)
.
If observing multiple properties (comma separated), the function receives only the new values, in the same order of the list.
// single property observer
@observe("name")
nameChanged(newName,oldName)
{
// ...
}
// multiple property observer
@observe("firstname,lastname")
fullnameChanged(newFirstName,newLastName)
{
// ...
}
Creates a computed property or sets the function for a computed property.
The easiest way is to decorate a function that takes as arguments the properties that are involved in the computed property.
In the following example, a computed property named "fullname" is created, based on the properties "firstName" and "lastName":
@computed()
fullname(firstName,lastName)
{
return firstName+" "+lastName; // firstname is the same as this.firstName
}
The decorator accepts also a map object for setting options on the property, e.g.:
@computed({ type: String })
fullname(firstName,lastName)
{
return firstName+" "+lastName;
}
The @computed
decorator is a shortcut for @property
:
@property({computed: 'computefullname(firstName,lastName)'})
fullname: string;
computefullname(firstName,lastName)
{
return firstName+" "+lastName;
}
Sets a listener function for an event.
In the following example the function resetCounter()
is called whenever the event reset-counters
is triggered (e.g. via fire()
).
@listen("reset-counters")
resetCounter() {
this.count = 0;
}
Incorporates behaviors from another object.
The object can be either a class (not necessarily a PolymerTS element) or a plain JavaScript object.
The @behavior
decorator can decorate the class
keyword or it can be put within the class itself.
Examples:
class MyBehavior extends polymer.Base
{
@listen("something_has_happened")
onBehave() {
console.log("something_has_happened triggered");
}
}
@component("my-element")
@behavior(MyBehavior)
class MyElement extends polymer.Base
{
// ...
}
or
@component("my-element")
class MyElement extends polymer.Base
{
@behavior(MyBehavior)
// ...
}
Note: a functionality similar to @behavior
can be also obtained by plain class inheritance
or by the use of Mixins.
It's also possible to create elements using TypeScript code only, without having any external .html. That can be useful if you want to keep template and logic in the same TypeScript file.
Use the tags @template
and @style
to specify the element's template and style, as in the following example:
@component("my-example")
// pass as argument what would be within <dom-module> and </dom-module>
@template(`<div>This element has been created completely from code</div>`)
// pass as argument what would be within <style> and </style>
@style(`:host { display: block; } div { color: red; }`)
class MyExample extends polymer.Base
{
// ...
}
MyExample.register();
Sets attributes on the host element.
In the following example, the style
attribute of the host element is changed:
@component("my-element")
@hostAttributes({ style: "color: red;" })
class MyElement extends polymer.Base
{
}
It's possible to avoid the use of decorators (e.g. for compatibility with TypeScript < 1.5) by simply writing their respective equivalent in plain Polymer syntax. E.g.
class MyElement extends polymer.Base
{
is = "my-element";
properties = {
myprop: { value: 42 }
};
// ...
}
@component("my-timer")
class MyTimer extends polymer.Base
{
@property({ type: Number, value: 0 })
public start: number;
public count: number;
private timerHandle: number;
constructor() {
this.count = this.start;
this.timerHandle = setInterval(() => {
this.count++;
}, 1000);
}
@observe("count")
countChanged(newValue, oldValue) {
if(newValue==100000) {
console.log("too much time spent doing nothing!");
this.fire("reset-counters");
}
}
@listen("reset-counters")
resetCounter() {
this.count = 0;
}
detatched() {
clearInterval(this.timerHandle);
}
}
MyTimer.register();
<dom-module id="my-timer">
<template>
<p>This is a timer element, and the count which started
from <span>{{start}}</span> is now: <span>{{count}}</span></p>
</template>
</dom-module>
To use the element
<my-timer start="42"></my-timer>
There are several (almost equivalent) ways of defining a computed property:
// classic way
@property({name: "fullname", computed: "computeFullName(first,last)"});
fullname: string;
computeFullName(f,l) {
return f+" "+l;
}
// by decorating a function
@property({computed: "first,last"});
fullname(f,l) {
return f+" "+l;
}
// by using @computed, name and parameters extracted from the function
@computed
fullname(first,last) {
return first+" "+last;
}
Elements can be instantiated by using a custom constructor:
@component("my-info")
class MyInfo extends polymer.Base
{
private someInfo: string;
constructor(someInfo: string) {
this.someInfo = someInfo;
}
}
// creates the element passing a parameter
var el = MyInfo.create("hello world");
// and attach in some way to the DOM
document.body.appendChild(el);
This example shows how to use a behavior defined in an external library (Polymer paper elements).
/// <reference path="typings/polymer/paper/PaperRippleBehavior.d.ts"/>
@component('ts-element')
@behavior(Polymer['PaperRippleBehavior'])
class TsElement extends polymer.Base implements Polymer.PaperRippleBehavior
{
// stand-in properties for behavior mixins
noink: boolean = false;
ensureRipple: (optTriggeringEvent?: Event) => void;
getRipple: () => paper.PaperRipple;
hasRipple: () => boolean;
handleClick(e:Event)
{
this.greet = "Holà";
this.fire("greet-event");
this.ensureRipple(e);
}
}
To run the "Test" project containing the Jasmine specs:
nippur72/PolymerTS
Test
directorybower update
In short, PolymerTS:
polymer.Base
that all your elements can extendregister()
in your element-class (to allow registration it in Polymer)in turn, the register()
method:
constructor()
before of the attached
event so that properties are correctly initializedconstructor(args)
to the factoryImpl()
callback so that custom constructor is processed correctlycreate()
methodget
and set
(Polymer's issue)<script>
on the main .html page (WebComponent's issue)Contributions are welcome.
If you find bugs or want to improve it, just send a pull request.
@behavior
to work with plain JavaScript objects (in addition to TypeScript classes)is
to Element's interfacePolymer.dom.flush()
polymer-ts.d.ts
to reference from external projectswebcomponents.js
(non-lite) in IEcreateElement()
and createClass()
deprecated, use Element.resgister()
instead<link rel="import">
to load PolymerTS and custom elementsclassName.register()
create()
on the element classconstructor()
is now a replacement of factoryImpl()
.implements polymer.Element
no longer requiredconstructor()
FAQs
Polymer 1.0 for TypeScript
We found that polymer-ts demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Maintainers back GitHub’s npm security overhaul but raise concerns about CI/CD workflows, enterprise support, and token management.
Product
Socket Firewall is a free tool that blocks malicious packages at install time, giving developers proactive protection against rising supply chain attacks.
Research
Socket uncovers malicious Rust crates impersonating fast_log to steal Solana and Ethereum wallet keys from source code.