3/22/13

Dynamic tabs with knockoutjs - part 1

Create a simple tabs widget with knockoutjs
Since we dealing with OOP javascript application we gonna use the knockoutjs library which is a very good framework for representing business objects in HTML.

First lets take care of html (view):

<script id="tabLinkTmpl" type="text/html">
<li data-bind="attr:{class:active},text:title,click:$parent.makeTabActive"></li>
</script>
<script id="tabPanelTmpl" type="text/html">
    <div class="content" tab="tab1" data-bind="visible: active()!='',html:content">
     
    </div>
</script>


  <ul class="tabs">
        <!--ko template: { name: 'tabLinkTmpl', foreach: tabsArr }--><!--/ko-->
  </ul>
<div class="contentWrap">
<!--ko template: { name: 'tabPanelTmpl', foreach: tabsArr }--><!--/ko-->
  </div>
<button data-bind="click:function(){ addTab('tab'+tabsArr().length,'','tabs count:'+tabsArr().length) }">Add New Tab</button>
   

Explanation:

For loading tab links and panels i'm using here templates. Templates are HTML code which is rendered by javascript and populated with data from business objects- View Models.
Speaking about View Models - here is the code of tabsViewModel:


var tabViewModel=function(title, active, content){ 
 this.title=ko.observable(title);
 this.active=ko.observable(active);
 this.content=ko.observable(content);
};
var tabsViewModel=function(){  
  this.tabsArr=ko.observableArray([]); 
  this.makeTabActive=function(data){
     //make all the tabs unactive
     $.each(this.tabsArr(),function(ind,item){
       item.active('');
  });
     //activate current tab  
     data.active('active');  
  }.bind(this);
  
  
  this.addTab=function(title, active, content){
    var nt=new tabViewModel(title, active, content);
 this.tabsArr.push(nt);
    this.makeTabActive(nt);
  }.bind(this);
};
var tabs=new tabsViewModel();
tabs.addTab('home','active', 'This is a home tab')
ko.applyBindings(tabs);


Explanation:
The tabs functionality includes two View Models: The tabViewModel - which represents the single tab entity, and tabsViewModel which responsible of managing all the tabs (like activating, creating etc)

At the result you get the knockoutjs based tabs widget:

you can download source from github
or see demo
Now, after we created functioning tabs widget -we ready to go to the next step

No comments:

Post a Comment

Getting started with docker

It is very simple to get started usig docker. All you need to do-is download the docker desktop for your system Once you get docker syste...