Buslowicz / twc

TypeScript based, boilerplate-less, Polymer toolbox friendly Polymer Modules
32 stars 1 forks source link

Setting default values for properties #38

Closed tpluscode closed 7 years ago

tpluscode commented 7 years ago

I've discovered that simply setting the property value is also processed into the default value in Polymer (at least targeting 1.x). It would be great to have this documented in the readme.

It should also be possible to set a function as the default value. Means to produce code like

Polymer({
  properties: {
    elements: {
      value: function() { return []; }
    }
 }
});

Maybe even an annotation with inline function?

export class MyContainer {
  @value(() => [])
  elements: Array;
}
Buslowicz commented 7 years ago

Sorry, forgot to mention that in readme :(. Assigning default value is simply assigning value to property in TypeScript:

export class MyElement {
    name: string = "value";
}

TWC automatically detects if the value assigned is a primitive value (string, number, boolean, null or undefined). If it is not primitive (variables, objects, arrays etc.) it wraps the value with a function:

export class MyElement {
    name: string = document.title;
}
export class MyElement {
    name: Array<string> = ["a", "b", "c"];
}

translates into

properties: {
  name: {type: String, value: function() { return document.title; } }
}
properties: {
  name: {type: Array, value: function() { return ["a", "b", "c"]; } }
}

I will update the readme with the above

tpluscode commented 7 years ago

Oh, that's very neat. Thanks!