Skip to content

Commit

Permalink
feat(prop): #12 instantiate prop when element is connected
Browse files Browse the repository at this point in the history
  • Loading branch information
geocine committed Jul 15, 2018
1 parent 08e8d69 commit fb5e197
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 6 deletions.
4 changes: 3 additions & 1 deletion src/custom-element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ export const CustomElement = (args: CustomElementMetadata) => {
const customElement: any = class extends (target as { new (): any }) {

static watchAttributes: {[key: string]: string};
props = {};
props: {[key: string]: any} = {};
__connected: boolean = false;

static get observedAttributes() {
return Object.keys(this.watchAttributes || {});
Expand All @@ -35,6 +36,7 @@ export const CustomElement = (args: CustomElementMetadata) => {
}

connectedCallback() {
this.__connected = true;
this.__render();
super.connectedCallback && super.connectedCallback();
}
Expand Down
13 changes: 9 additions & 4 deletions src/prop.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
export const Prop = (): any => {
return (target: any, propName: any) => {
function get() {
if (!this.props) {
this.props = {};
}
return this.props[propName] || this.getAttribute(propName);
}
function set(value: any) {
const oldValue = this[propName];
this.props[propName] = value;
if(typeof value != 'object'){
this.setAttribute(propName, value);
} else {
this.attributeChangedCallback(propName, oldValue, value);
if(this.__connected){
if(typeof value != 'object'){
this.setAttribute(propName, value);
} else {
this.attributeChangedCallback(propName, oldValue, value);
}
}
}
Object.defineProperty(target, propName, { get, set });
Expand Down
2 changes: 1 addition & 1 deletion tests/decorators.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { CustomElement, Watch, Prop } from 'custom-elements-ts';
})
export class MyElement extends HTMLElement {

@Prop() name;
@Prop() name = 'my element';

@Watch('name')
setSpan(_: string, newValue: string){
Expand Down

0 comments on commit fb5e197

Please sign in to comment.