Polymer 1.1 Cheat Sheet

A cheat sheet in English by Pawel

Polymer 1.1 cheat sheet

11,957 views 2,867 downloads 6 Feb 2016 History
3.7 avg · 0 ratings

Register and Create

**// Register element 'my-element' and return constructor**
var elementConstr = Polymer({is: 'my-element'})

**// Register element 'my-element' with factory implementation**
**var** elementConstr = **Polymer**(
{ **is**: 'my-element',
  **factoryImpl**: function (v1, v2) {
    this.v1 = v1;
    this.v2 = v2
}});

**// Create element**
**var** myElement = new elementConstr();
**OR**
**var** myElement = document.createElement('my-element');

**Create element with factory implementation**
**var** myElement = new elementConstr(1, 2);

Extend existing element

**// Extend existing input element**
**var** myElement = **Polymer**({
   **is**: 'my-input',
   **extends**: 'input'
});

Data binding

{{prop}}
bind property '­pro­p', get child custom element notifi­cations
[[prop]]
bind property '­pro­p', DO NOT get child custom element notifi­cations
{{prop::eventname}}
bind property '­pro­p' when event '­eve­ntn­ame­' occurs
{{obj.prop}}
bind property '­pro­p' of '­obj­' object property
{{!bool}}
negate and bind boolean property '­boo­l'
{{compute(a, b)}}
execute '­com­pute(a, b)' and bind
<my­-el­ement selected$="{{value}}"></my-element>
bind '­val­ue' to attribute '­sel­ect­ed'
<my­-el­ement selected="{{value}}"></my-element>
bind '­val­ue' to property '­sel­ect­ed'

Behaviors

**my-behavior.html**
<script>
myBehavior = {
    **listeners**: {'click' : 'changeColor'},
    **changeColor**: function () {
       this.color = 'blue';    
     }
}
</script>
**my-element.html**
<link rel="import" href="my-behavior.html">
**Polymer**({
  **is**: 'my-element',
  **behaviors**: [myBehavior]
});

Register observers

 **Polymer**({
        **is**: 'my-element',
        **properties**: {
            *color*: String,
            *arr*: {
                **type**: Array,
                **value**: function () {return [];}
            },
            *obj*: {
                **type**: Object
            }
        },
        **observers**: [
    'obs1(obj.prop2)', 'obj2(color)',
    'obs3(obj.prop2, color)', **//Observe mupliple**
    'obs4(obj.*) **//Observe deep**,
    'obs5(arr.splices) **//Observe array splices**
        ]});

Debouncing

**Polymer**({
  **is**: 'my-element',
  **properties**: {
    prop1: String,
    prop2: String
  },
  **observers**: ['doSomething(prop1, prop2)'],
  **doSomething**: function () {
    **this.debounce**('doSomething', function () {
      console.log('called once...');
    }, 300);
  }
});
When '­pro­p1' and '­pro­p2' are changed within 300ms time frame, '­doS­ome­thi­ng' callback is executed once.

Lifecycle Callbacks

created
when element is registered
ready
when element is registered and local DOM is ready
attached
when element is attached to DOM
detached
when element is removed from DOM
attrib­ute­Changed
when element attribute is changed

Styling

:host
style host element
:host ::content
style distri­buted content
--cust­om-­pro­perty: value
create css property '­cus­tom­-pr­ope­rty­' and give it a '­val­ue'
--mixi­n-name: {mixin contents}
create mixin '­mix­in-­nam­e' with contents '­mixin conten­ts'
color: var(--­my-­color, red)
apply custom property 'my color', set default to red
color: @apply­(--­mix­in-­name)
apply mixin '­mix­in-­nam­e' to a property '­col­or'

Import styles

**style.html**
<**dom-module** id="my-style">
    <template>
        <style>
            :host {
                --text-style: blue;
            }
        </style>
    </template>
<**/dom-module**>

**my-element.html**
<**link rel="import" href="style.html"**>
<**dom-module** id="my-element">
    <style **include="my-style"**></style>
<**/dom-module**>



Style from light DOM

<**style** is="custom-style">

        my-element {
            --text-style: red;
        }

<**/style**>

Dom repeat

**<template is="dom-repeat" items={{table}} as="myTable">**
<div>{{myTable.item}}</div>
**</template>**
...
**Polymer** ({ ...
     ready: function () {this.table = [{item: 'item1'}, {item: 'item2'}];}
...});

Sort and Filter

<template is="dom-repeat" items={{table}} **filler="myFilter" sort="mySort"**>
<div>{{table.item}}</div>
</template>
...
**Polymer** ({ ...
     **ready**: function () {this.table = [{item: 'item1'}, {item: 'item2'}];},
     **myFilter**: function (item) {...},
     **mySort**: function (item) {...}
...});

Extending Behaviors

<link rel="import" href="oldbehavior.html">
<script>
  NewBehaviorImpl = {
  }
  **NewBehavior = [ OldBehavior, NewBehaviorImpl ]**
</script>

Add event listeners

**// Add event listeners as a element prototype property**
<dom-module id="my-element">
<template>
    <**div** id="elementID1">Element 1<**/div**>
    <**div** id="elementID2">Element 1<**/div**>
</template>
</dom-module>
{
   **Polymer**({
    **is**: 'my-element',
    **listeners**: {
       'click.elementID1' : 'handleClick1',
       'click.elementID2' : 'handleClick2'
       'click' : 'handleClick' **// Every click**
});

**// Adding event listeners on elements**
<element on-{event name} = "{handler}"></element>

Observe mutations

this._observer = **Polymer.dom**(this).
      **observeNodes**(function (info) {
                console.log ('Added nodes: ' + info.**addedNodes**);
                console.log ('Removed nodes: '+ info.**removedNodes**);
});

**Polymer.dom**(this).**unobserveNodes**(this._observer)

Property Definition

type
type of a property (String, Array, Boolean, Number, Object)
value
default value
readOnly
set read only property
notify
fire '­pro­per­ty-­cha­nge­d' event, when property is changed. Handy for nested data binding
reflec­tTo­Att­ribute
update attribute when property is changed
observer
execute provided Callback when property is changed
computed
compute value based on other property values
Example for color and underline proper­ties:
properties: {
color: String,
underline: {
type: Boolean,
value: false,
observer: '­app­lyD­eco­rat­ion­',
reflec­tTo­Att­ribute: true,
notify: true
}

Property modifi­cations

this.s­et(­'­pro­per­ty', value)
set this.p­roperty to '­val­ue'
this.s­et(­'­arr.1', value)
set this.a­rr[1] to '­val­ue'
this.s­et(­'­obj.pr­op1­', value)
set this.o­bj.p­rop1 to '­val­ue'
this.g­et(­'­pro­per­ty')
get value of this.p­roperty
this.g­et(­'­obj.pr­op1­')
get value of this.o­bj.p­rop1
this.g­et(­'­arr.1')
get value of this.a­rr[1]
This API is required to observe properties of Array and Object types.

Polymer API

Dom manipu­lation
Polyme­r.d­om(­ele­ment).method
Shadow root
this.root
Host element
this
this.$.myid
local DOM element with id = '­myi­d'
this.$­$(s­ele­ctor)
"­que­ryS­ele­cto­r" in local DOM
conten­tEl­eme­nt.g­et­Dis­tri­but­edN­odes()
return distri­buted nodes to conten­tEl­ement
elemen­t.g­etD­est­ina­tio­nIn­ser­tio­nPo­ints()
return <co­nte­nt> elements for light DOM '­ele­men­t', where '­ele­men­t' is distri­buted to local DOM
conten­tEl­eme­nt.g­et­Con­ten­tCh­ild­ren()
return distri­buted elements to local DOM that are children of '­con­ten­tEl­eme­nt'
.{query | get}Ef­fec­tiv­eCh­ild­ren()
return effective children Handy for nesting when host element contains <co­nte­nt> tag
.getEf­fec­tiv­eCh­ild­Nodes()
same as above for nodes

Condit­ional Template

**<template is="dom-if" if="{{user.isAdmin}}">**
      Only admins can see this.
**</template>**

Utility Functions

toggle­Class()
toggle class
toggle­Att­rib­ute()
toggle attribute
attrib­ute­Fol­lows()
move attribute from one element to another
classF­oll­ows()
move class from one element to another
async()
call asynch­ron­ously
fire()
dispatch event
cancel­Deb­oun­cer()
cancel given debouncer
flushD­ebo­uncer()
call debouncer task and cancel debouncer
isDebo­unc­erA­ctive()
return true if active, false otherwise
transf­orm()
tranform element (css transform function)

Badges

Nice Cheat Sheet Good Cheat Sheet Downloaded from Unusual Locations × 1

Comments

No comments yet.

Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.