Daniel Earwicker
Daniel Earwicker

Reputation: 116714

Can knockout.js components be treated polymorphically?

From what I've read regarding the components feature just added in Knockout 3.2, the examples assume that the consumer of a component specifies what type it is.

Is there some way for the consumer to say "component goes here" without specifying a type, and for the component's identity to be encapsulated in a property of the consumer's view model?

Background:

I have a control binding I've been using:

data-bind="control: weirdEditor"

The weirdEditor observable property has to contain an object with a ui string property, which contains the HTML for its view. The object itself is the view model. The control binding binds them together and inserts the resulting self-contained UI component in the containing element.

Looking around for similar patterns, it looks like Durandal has a compose binding that is pretty close:

data-bind="compose: { model: wierdEditor, view: wierdEditor().ui() }

Except that (I think) ui would have to be a path to some HTML resource in their AMD-based module system. I just make it an HTML string that I can require with a suitably extended CommonJS.

The advantage is that you can create generic containers (a splitter between two panes, a system of tabs, a grid with editable cells) such that the container is unaware of what it is acting as a container for. It can contain anything (and the contents can be replaced at any time).

Upvotes: 2

Views: 240

Answers (1)

Michael Best
Michael Best

Reputation: 16688

The component binding does support using an observable for the component name.

data-bind="component: weirdEditor"

Upvotes: 1

Related Questions