DEV Community

Cover image for How to manage sub views for an array data - craftkit best practice
CraftkitJS
CraftkitJS

Posted on • Updated on

How to manage sub views for an array data - craftkit best practice

Sometimes, your sub-views has listed view created by array data.

In such case, you have two choice to create view for them. One is make loop in the template, one is break down to simple view.

Here is a comparison of sample product list:

var products = [
    { name: 'Apple', price: 10 },
    { name: 'Orange', price: 13 },
    { name: 'Strawberry', price: 20 },
    { name: 'Pear', price: 9 }
];
Enter fullscreen mode Exit fullscreen mode

Loop pattern

class ProductList extends Craft.UI.View {
    constructor(options){
        super(options);
        this.data = { products:options.products };
        this.views = {};
    }
    template(componentId){
        return `
            <div id="root" class="root">
                ${ this.data.products.map( (product,idx) => `
                    <div id="idx" class="product">
                        ${product.name} : ${product.price}
                    </div>
                `).join('')}
            </div>
        `;
    }
}
Enter fullscreen mode Exit fullscreen mode

Factorize pattern

class Product extends Craft.UI.View {
    constructor(options){
        super(options);
        this.data = options;
        this.views = {};
    }
    template(componentId){
        return `
            <div id="root" class="root">
                ${this.data.name} : ${this.data.price}
            </div>
        `;
    }
}

class ProductList extends Craft.UI.View {
    constructor(options){
        super(options);
        this.data = { products:options.products };
        this.views = { products:[] };
    }
    viewDidLoad(callback){
        this.data.products.forEach( p => {
            let view = new Product(p);
            this.appendView(view);
            this.views.products.push(view);
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

Write looping block directly in the template method is shorter than Factorise pattern. But when you control product view after appended it, you have to write something like this:

var target = this.shadow.getElementById('1');
target.root.style.color = 'red';
Enter fullscreen mode Exit fullscreen mode

Or, you have to get the idx from the product map. This is only useful for a quick program and simple list.

Therefore, the best practice of managing sub-views for an array data is Factorise pattern.

Always, this brings good results and ease to maintain.

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

Top comments (0)