A StealJS plugin for CanJS components. done-component allows you to easily define your component completely from a single .component
file:
npm install done-component --save
Define a can.Component in a separate file:
<can-component tag="hello-world">
<style type="text/less">
i {
color: red;
}
</style>
<template>
{{#if visible}}<b>{{message}}</b>{{else}}<i>Click me</i>{{/if}}
</template>
<script type="view-model">
export default {
visible: true,
message: "Hello There!"
};
</script>
<script type="events">
export default {
click: function(){
this.viewModel.attr("visible", !this.viewModel.attr("visible"))
}
};
</script>
</can-component>
In your template simply import your component and you can start using it:
<can-import from="hello-world.component!"/>
<hello-world></hello-world>
The tag name is specified on the can-component
element. This corresponds to tag
when defining a Component in JavaScript.
<can-component tag="foo-bar">
</can-component>
This defines a custom element "foo-bar" when you can use in your templates:
<foo-bar></foo-bar>
The leak-scope attribute is equivalent to setting leakScope: true
using can-component directly.
<can-component tag="foo-bar" leak-scope>
</can-component>
Is equivalent to writing:
Component.extend({
tag: "foo-bar",
leakScope: true
});
The <style>
tag lets you include CSS specific to your component. By default it will use the CSS plugin but you can use preprocessors by specifying:
The style type lets you use an alternative to CSS such as Less:
<style type="text/less">
span {
color: red
}
</style>
Not that when using Less your style is automatically wrapped with the Component's tag name, so that it is scoped to only your component.
The <template>
tag is where you put your Stache template.
The <view-model>
or <script type="view-model">
is where you put your viewModel. You can use either method, but the <script>
method is more compatible with your editor.
The <events>
or <script type="events">
is where you put your events object.
The <helpers>
or <script type="helpers">
is where you put Stache helpers.
Each of the subtags (style, template, view-model, events, and helpers) can optionally take a from=
attribute that allows you to define that in a separate module. It's useful if one part is longer and you want to separate that out into it's own file:
<can-component tag="foo">
<view-model from="foo/view_model"/>
</can-component>
Your .component
will export an object that contains properties for Component
which is the can.Component constructor, ViewModel
which is a can.Map of your exported ViewModel. This is useful for when testing:
var QUnit = require("steal-qunit");
var HelloVM = require("hello-world.component!").ViewModel;
QUnit.test("view model works", function(){
var map = new HelloVM();
...
});
MIT