DEV Community

Cover image for How to define instance data in your view - craftkit best practice
CraftkitJS
CraftkitJS

Posted on • Edited on

How to define instance data in your view - craftkit best practice

When you make view class that hold instance data, like data from user action, data from server, and so on, you can hold those data anywhere you want.

But the best practice of managing instance data of Craft.UI.View sub-class is to set them into this.data.

Craft.UI.View and its super-class Craft.Core.Component has many field by default. Those fields are designed to not conflict with user land usage. But sometimes it might be occurred.

To prevent field confliction, you are recommended to set your instance data in this.data.

Example:

class HeaderTitle extends Craft.UI.View {
    constructor(options){
        super(options);
        this.data = {
            title : options.title
        };
    }
    template(componentId){
        return `
            <div id="root" class="root">
                <h1>${this.data.title}</h1>
            </div>
        `;
    }
}
Enter fullscreen mode Exit fullscreen mode

When you make sub-class of HeaderTitlte, it is recommended to define its own this.data.

class SmallHeaderTitle extends HeaderTitle {
    constructor(options){
        super(options);
        this.data = {
            title : options.title
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

But you can cascade super-class this.data if you need.

class DualHeaderTitle extends HeaderTitle {
    constructor(options){
        super(options);
        this.data = Object.assign(
            {
                sub: options.subtitle 
            },
            this.data
        );
    }
    template(componentId){
        return `
            <div id="root" class="root">
                <h1>${this.data.title}</h1>
                <h2>${this.data.sub}</h2>
            </div>
        `;
    }
}
Enter fullscreen mode Exit fullscreen mode

Further more:

When you would like to apply observer observable pattern like using Proxy, just you have to watch is change of this.data.

🛺 Try CraftKit Playground:
https://github.com/craftkit/craftkit-playground

Top comments (0)