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

AWS Q Developer image

Your AI Code Assistant

Implement features, document your code, or refactor your projects.
Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

If you found this article helpful, a little ❤️ or a friendly comment would be much appreciated!

Got it