v4.2.0
This release makes it possible to create new component instances with new
, without rendering the instances in a template. This is useful when you:
- have complex logic for switching between different components (e.g. routing)
- want to create components without adding them to the page (e.g. testing)
The following defines a MyGreeting
component and creates a my-greeting
element by calling new
on the component’s constructor function:
const HelloWorld = Component.extend({
tag: "hello-world",
view: `
<can-slot name="greetingTemplate" />
<content>world</content>
<ul>{{#each(items)}} {{this}} {{/each}}</ul>
`,
ViewModel: {
items: {}
}
});
// Create a new instance of our component
const componentInstance = new HelloWorld({
// values with which to initialize the component’s view model
viewModel: {
items: ["eat"]
},
// can-stache template to replace any <content> elements in the component’s view
content: "<em>{{message}}</em>",
// <can-template> strings rendered by can-stache with the scope
templates: {
greetingTemplate: "{{greeting}}"
},
// scope with which to render the <content> and templates
scope: {
greeting: "Hello",
message: "friend"
}
});
myGreetingInstance.element; // is like <my-greeting>Hello <em>friend</em> <ul> <li>eat</li> </ul></my-greeting>
myGreetingInstance.viewModel; // is HelloWorld.ViewModel{items: ["eat"]}
Changing the component’s view model will cause its element and any bindings to be updated:
myGreetingInstance.viewModel.items.push("sleep");
myGreetingInstance.element; // is like <my-greeting>Hello <em>friend</em> <ul> <li>eat</li> <li>sleep</li> </ul></my-greeting>
See the Programmatically instantiating a component section for details.
This release contains the following pull requests:
- Allow components to be instantiated with
new
#237 - Add support for rendering components in stache templates #238
- Allow components to be instantiated with
<content />
#240 - Allow components to be instantiated with viewModel bindings #243
- Allow components to be instantiated with slot templates #267
- Add "use strict" #269