can.Component.extend({
tag: "tabs",
template:
"<ul>"+
// For each panel, create an LI.
"{{#panels}}"+
"<li {{#isActive}}class='active'{{/isActive}} "+
"can-click='makeActive'>"+
"{{title}}"+
"</li>"+
"{{/panels}}"+
"</ul>"+
// Render the original content.
"<content></content>",
scope: {
// contains palen objects
panels: [],
// Use to add a panel
addPanel: function(panel){
// If this is the first panel, make it active
if( this.attr("panels").length === 0 ) {
this.makeActive(panel)
}
this.attr("panels").push(panel);
},
// Use to remove a palenl
removePanel: function(panel){
var panels = this.attr("panels");
// batch these changes so DOM changes
// happen together
can.batch.start();
panels.splice(panels.indexOf(panel),1);
if(panel === this.attr("active")){
if(panels.length){
this.makeActive(panels[0]);
} else {
this.removeAttr("active")
}
}
can.batch.stop()
},
// sets the active panel
makeActive: function(panel){
this.attr("active",panel);
this.attr("panels").each(function(panel){
panel.attr("active", false)
})
panel.attr("active",true);
},
// If agiven panel is active
isActive: function( panel ) {
return this.attr('active') == panel
}
}
});
can.Component.extend({
template: "{{#if active}}<content></content>{{/if}}",
tag:"panel",
scope: {
active: false
},
events: {
// When the element is inserted, add its data to the tabs
inserted: function(){
this.element.parent().scope().addPanel( this.scope );
},
removed: function(){
this.element.parent().scope().removePanel( this.scope );
}
}
})
var foodTypes= new can.List([
{title: "Fruits", content: "oranges, apples"},
{title: "Breads", content: "pasta, cereal"},
{title: "Sweets", content: "ice cream, candy"}
])
$("#out").html( can.view("app",{
foodTypes: foodTypes,
addVegies: function(){
foodTypes.push({
title: "Vegetables",
content: "Carrots, peas, kale"
})
}
}) )
<div id='out'></div>
<script id="app" type="text/mustache">
<p><button can-click="addVegies">Add Vegetables</button></p>
<tabs>
{{#each foodTypes}}
<panel title='title'>{{content}}</panel>
{{/each}}
</tabs>
</script>
body {font-family: verdana}
tabs {
margin-top: 20px;
}
button {clear: both;}
tabs ul {
padding: 0px; margin: 0px;
}
tabs li {
float: left;
padding: 10px;
background-color: #F6F6F6;
list-style: none;
margin-left: 10px;
}
tabs li {
color: #1C94C4;
font-weight: bold;
text-decoration: none;
}
tabs li.active {
color: #F6A828;
cursor: default;
}
panel {
clear: both;
display: block;
}
/* clearfix from jQueryUI */
tabs ul:after { content: "."; display: block; height: 1px; clear: both; visibility: hidden; }
tabs ul { display: inline-block; }
External resources loaded into this fiddle: