Skip to content

Add "createTemplate" to Component Templates analogous to createViewModel #1458

@sccooper

Description

@sccooper

I would like custom elements to be allowed to define just a view model and leave the template up to a 3rd party designer on a per element basis, so templates for components could use the html between the custom element tags or be specified as a parameter, e.g.:

<my-component>
<span data-bind="text: foo"></span>
</my-component>

or:

<my-component params="custom-template: 'custom-id'"></my-component>

I added this functionality by allowing templates to have a createTemplate property when registering custom elements that is a function that takes (data, info) like createViewModel does.

I can then implement the functionality I want like this:

ko.components.register("my-component", {
    viewModel: { ... },
    template: {
        createTemplate: function (data, info) {
            if (data["something"]) {
                return "<something></something>";
            } else {
                return {
                    element: info.element
                };
            }
        }
    }
});

I think this approach is generally useful, but it does affect loaded configs which now have a createTemplate property when resolved, not a template property that is an array of nodes. I have tried to handle existing loaders by first looking for the template property.

Would you like to see the patch or is there a better way of doing this?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions