can
Version:
MIT-licensed, client-side, JavaScript framework that makes building rich web applications easy.
400 lines (348 loc) • 15.6 kB
HTML
<!--####################################################################
THIS IS A GENERATED FILE -- ANY CHANGES MADE WILL BE OVERWRITTEN
INSTEAD CHANGE:
source: [object Object]
@page BuildWidgets
######################################################################## -->
<html lang="en">
<head>
<meta charset="utf-8">
<title>CanJS - Build Widgets/UI Elements</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<link rel="stylesheet" type="text/css" href="./static/bundles/bit-docs-site/static.css">
<link rel="shortcut icon" sizes="16x16 24x24 32x32 48x48 64x64" href="/docs/images/canjs_favicon.ico">
<link rel="apple-touch-icon" sizes="57x57" href="../docs/images/canjs_favicon_57x57.png">
<link rel="apple-touch-icon-precomposed" sizes="57x57" href="../docs/images/canjs_favicon_57x57.png">
<link rel="apple-touch-icon" sizes="72x72" href="../docs/images/canjs_favicon_72x72.png">
<link rel="apple-touch-icon" sizes="114x114" href="../docs/images/canjs_favicon_114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="../docs/images/canjs_favicon_128x128.png">
<link rel="apple-touch-icon" sizes="144x144" href="../docs/images/canjs_favicon_144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="../docs/images/canjs_favicon_152x152.png">
<meta content="yes" name="apple-mobile-web-app-capable">
<meta name="apple-mobile-web-app-status-bar-style" content="white-translucent">
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-2302003-11', 'auto');
ga('send', 'pageview');
</script>
</head>
<body>
<input type="checkbox" id="nav-trigger" class="nav-trigger"/>
<label for="nav-trigger">Menu</label>
<div id="everything">
<div id="left" class="column">
<div class="top-left">
<div class="brand">
<div class="logo">
<a href="../index.html" alt="CanJS"></a>
<div class="dropdown project-dropdown">
<a href="https://donejs.com/">DoneJS</a>
<a href="http://stealjs.com/">StealJS</a>
<a href="http://jquerypp.com/">jQuery ++</a>
<a href="https://funcunit.com/">FuncUnit</a>
<a href="http://documentjs.com/">DocumentJS</a>
</div>
</div>
<div class="version">
<div class="version-number">
3.0.0
</div>
<div class="dropdown version-dropdown">
<a href="https://v2.canjs.com">2.3.27</a>
</div>
</div>
</div>
<div class="search-bar">
<p>
</p>
</div>
</div>
<div class="bottom-left">
<div class="social-side-container">
<ul class="social-side">
<li>
<a class="header-mobile github" href="https://github.com/canjs/canjs" target="_blank"><img class="social-icon-small" src="../docs/images/github.png">Github</a>
</li>
<li>
<a class="header-mobile twitter" href="https://twitter.com/canjs" target="_blank"><img class="social-icon-small" src="../docs/images/twitter.png">Twitter</a>
</li>
</ul>
<ul class="social-side">
<li>
<a class="header-mobile" href="https://gitter.im/canjs/canjs" target="_blank">Chat</a>
</li>
<li>
<a class="header-mobile" href="http://forums.donejs.com/c/canjs" target="_blank">Forum</a>
</li>
</ul>
</div>
</div>
</div>
<div id="right" class="column">
<div class="top-right">
<div class="top-right-top">
<ul class="top-right-bitovi">
<li class="dropdown">
<a href="http://bitovi.com" class="bitovi icon-bits">Bitovi</a>
<ul class="dropdown-menu">
<li><a href="http://bitovi.com">Bitovi.com</a></li>
<li><a href="http://bitovi.com/blog/">Blog</a></li>
<li><a href="http://bitovi.com/consulting/">Consulting</a></li>
<li><a href="http://bitovi.com/training/">Training</a></li>
<li><a href="http://bitovi.com/open-source/">Open Source</a></li>
</ul>
</li>
</ul>
<div class="brand">
<div class="logo">
<a href="../index.html" alt="CanJS"></a>
</div>
</div>
<ul class="top-right-links">
<li>
<a href="https://gitter.im/canjs/canjs">Chat</a>
</li>
<li>
<a href="http://forums.donejs.com/c/canjs">Forum</a>
</li>
<li>
<a class="github-button nav-social" href="https://github.com/canjs/canjs" data-count-href="/canjs/canjs/stargazers" data-count-api="/repos/canjs/canjs#stargazers_count">Star</a>
</li>
<li>
<a href="https://twitter.com/canjs" class="twitter-follow-button nav-social" data-show-count="true" data-show-screen-name="false">Follow @canjs</a><script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
</li>
</ul>
</div>
<div class="breadcrumb">
<li><a href="BuildWidgets.html">Build Widgets/UI Elements</a></li>
<li class="breadcrumb-dropdown">/ <a> On this page</a>
<ul class="on-this-page"></ul>
</li>
<div class="nav-toggle" title="Back to top"></div>
</div>
</div>
<div class="bottom-right">
<article>
<section class="title">
<div class="page-type">
<h1>Build Widgets/UI Elements</h1>
<div>page</div>
</div>
<section class="description">
</section>
</section>
<section class="on-this-page-table">
</section>
<section class="title-footer">
<ul class="title-links">
<!-- <li><a href="#">docco</a></li> -->
<li><a href="//github.com/canjs/canjs/tree/v3.0.0/docs/can-guides/recipes/build-widgets.md">source</a></li>
<!-- <li><a href="#">download</a></li> -->
<!-- <li><a href="#">tests</a></li> -->
</ul>
</section>
<section class="body">
<p>Previous recipes have demonstrated how to change page content and introduced
event handling. The following recipes will introduce <code>can.Component</code>,
which allows for straightforward widget construction by packaging
template, state, and event handling code in one place.</p>
<p>While similar <em>behavior</em> can be accomplished with <code>can.Control</code>,
building a Component enables building reusable widgets using custom
HTML tags.</p>
<h2>Create a Component</h2>
<p>The previous recipe that displays a list of people can instead
be represented as a component.</p>
<pre><code><people></people>
</code></pre>
<p>By specifying <code>people</code> as the tag, a component is created wherever <code><people></people></code>
appears in a template.</p>
<pre><code>can.Component.extend({
tag: 'people',
</code></pre>
<p>The <code>scope</code> object on a <code>Component</code> contains the component's state, data,
and behavior. Here, it specifies how to <code>remove</code> a person from the list:</p>
<pre><code> scope: {
people: people,
remove: function( person ) {
var people = this.attr("people");
var index = people.indexOf(person);
people.splice(index, 1);
}
}
});
</code></pre>
<p>The template for the component itself is passed via the <code>template</code>
property. This can either be an external file or a string.
Each <code>li</code> uses <code>can-click</code>, <a href="http://canjs.com/docs/can.view.bindings.can-EVENT.html">which declares an event binding.</a>
Here, <code>remove</code> inside the component's
scope will be called with the relevant <code>people</code> object
as an argument.</p>
<pre><code>scope: {
template: '<ul>' +
'{{#each people}}' +
'<li can-click="remove">' +
'{{lastname}}, {{firstname}}' +
'</li>' +
'{{/each}}' +
'</ul>',
...
</code></pre>
<p>This behaves similarly to the <code>can.Control</code> from above.
However, the <code><people></code> tag can be used without having
any knowledge about the inner workings of the widget.
Using declarative HTML tags, a component can be used
without writing any javascript. The template, state,
and behavior are all combined into one Component.</p>
<iframe width="100%" height="300" src="http://jsfiddle.net/donejs/WBM9z/embedded/result,html,js/" allowfullscreen="allowfullscreen" frameborder="0"> </iframe>
<h2>Build a Tabs Widget</h2>
<p>A tabs widget could be instantiated with the following HTML:</p>
<pre><code><tabs>
<panel title="Fruit">Oranges, Apples, Pears</panel>
<panel title="Vegetable">Carrot, Lettuce, Rutabega</panel>
<panel title="Grains">Bread, Pasta, Rice</panel>
</tabs>
</code></pre>
<p>A designer that understands HTML can put together a template for a <code>tabs</code>
widget without understanding anything other than the syntax.
This is one of the most useful features of components.</p>
<h2>Tabs Widget Behavior</h2>
<p>Before implementing the component itself, we’ll
define an observable <em>view model</em>--the <code>scope</code> object
of the UI element. This makes the code modular and easier
to manage (and also allows for unit testing).</p>
<p>In order to accurately represent a tabs widget,
a <code>TabsViewModel</code> needs:</p>
<ul>
<li>An observable list of panels</li>
<li>A state variable with the active panel</li>
<li>Helper methods to add, remove, and activate panels</li>
</ul>
<p>Since TabsViewModel is a <code>can.Map</code>, the <code>panels</code> property is
automatically converted to a <code>can.List</code>.
The <code>active</code> property references the <code>panel</code> object
that should currently be displayed.</p>
<pre><code>var TabsViewModel = can.Map.extend({
panels: [],
active: null,
addPanel: function( panel ){
var panels = this.attr("panels");
panels.push(panel);
panel.attr("visible", false);
//activate panel if it is the first one
if ( panels.attr("length") === 1 ){
this.activate( panel );
}
},
removePanel: function( panel ){
var panels = this.attr("panels");
var index = panels.indexOf(panel);
panels.splice(index, 1);
//activate a new panel if panel being removed was the active panel
if( this.attr("active") === panel ){
panels.attr("length") ? this.activate(panels[0]) : this.attr("active", null)
}
},
activate: function( panel ){
var active = this.attr("active")
if( active !== panel ){
active && active.attr("visible", false);
this.attr("active", panel.attr("visible", true));
}
}
});
</code></pre>
<h3>Tabs Widget Component</h3>
<p>Now that the view model is defined, making a component is simply
a matter of defining the way the tabs widget is displayed.</p>
<p>The template for a <code>tabs</code> component needs a list of panel titles
that will <code>activate</code> that panel when clicked. By calling <code>activate</code>
with a panel as the argument, the properties of the <code>panel</code> can
be manipulated. By changing the <code>visible</code> property of a panel,
a template can be used to display or hide the panel accordingly.</p>
<p>For this component, our template should look something like this:</p>
<pre><code><tabs>
<panel title="Fruits">Apples, Oranges</panel>
<panel title="Vegetables">Carrots, Celery</panel>
</tabs>
</code></pre>
<p>A designer can create a <code>tabs</code> component with <code>panel</code> components inside it.
The <code>template</code> object on the tabs component's scope needs to be able to render
the content that is inside of the <code><tabs></code> tag. To do this, we simply use the
<code><content></code> tag, which will render everything within the component's tags:</p>
<pre><code>can.Component.extend({
tag: "tabs",
scope: TabsViewModel,
template: "<ul>\
{{#each panels}}\
<li can-click='activate'>{{title}}</li>\
{{/each}}\
</ul>\
<content />"
});
</code></pre>
<p>The <code>tabs</code> component contains panels, which are also defined
as components. The tabs template contains the logic for whether
the panel is visible (<code>visible</code> is controlled by the tabs
component's <code>activate</code> method).</p>
<p>Each panel's <code>scope</code> contains a title, which should be
taken from the <code>title</code> attribute in the <code><panel></code> tag.
If you want to set the string value of a Component's
attribute as a <code>scope</code> variable, use <code>@'</code>.</p>
<pre><code>can.Component.extend({
tag: "panel",
template: "{{#if visible}}<content />{{/if}}",
scope: {
title: "@"
},
...
</code></pre>
<p>In addition to the <code>scope</code> property, a component has an
<a href="http://canjs.com/docs/can.Component.prototype.events.html"><code>events</code> property</a>.
This <code>events</code> property uses a <code>can.Control</code> instantiated inside
the component to handle events.</p>
<p>Since we defined behavior for adding panels on the parent
<code>tabs</code> component, we should use this method whenever a <code>panel</code>
is inserted into the page (and an <code>inserted</code> event is triggered).
To add the panel to the <code>tabs</code> component's scope, we call the
<code>addPanel</code> method by accessing the parent scope with <code>this.element.parent().scope()</code>:</p>
<pre><code>...
events: {
inserted: function() {
this.element.parent().scope().addPanel( this.scope )
},
removed: function() {
this.element.parent().scope().addPanel( this.scope )
}
}
});
</code></pre>
<p>With this component, any time a <code><tabs></code> element with
<code><panel></code> elements is put in a page, a tabs widget will
automatically be created. This allows application behavior
and design to be compartmentalized from each other.</p>
<iframe width="100%" height="300" src="http://jsfiddle.net/x6TJK/2/embedded/result,html,js/" allowfullscreen="allowfullscreen" frameborder="0"> </iframe>
</section>
<script type="text/javascript">
var docObject = {"src":{"path":"docs/can-guides/recipes/build-widgets.md"},"description":"\n","name":"BuildWidgets","title":"Build Widgets/UI Elements","type":"page","parent":"Recipes","order":5,"comment":" ","pathToRoot":".."};
</script>
</article>
<footer><p>CanJS is part of <a href="http://donejs.com" target="_blank">DoneJS</a>. Created and maintained by the core <a href="https://donejs.com/About.html#section=section_Team" target="_blank">DoneJS team</a> and <a href="http://bitovi.com" target="_blank">Bitovi</a>. <strong>Currently 3.0.0.</strong></p></footer>
</div>
</div>
</div>
<script>
steal = {
instantiated: {
"bundles/bit-docs-site/static.css!$css" : null
}
};
</script>
<script type='text/javascript' data-main="bit-docs-site/static" src="./static/node_modules/steal/steal.production.js"></script>
<script async defer src="https://buttons.github.io/buttons.js"></script>
</body>
</html>