3/22/13

Dynamic tabs with knockoutjs - part 3

Gettig all the widgets to work together
Now lets make some slight modifications to tabsViewModel so it will be able to host
the widgets from previous post:

var tabViewModel=function(title, active, model, templateName){ 
  this.title=ko.observable(title);
  this.active=ko.observable(active);
  this.model=ko.observable(model);
  this.templName=templateName;
};
var tabsViewModel=function(){  
  this.tabsArr=ko.observableArray([]); 

 
  this.makeTabActive=function(data){

    
      $.each(this.tabsArr(),function(ind,item){
       item.active('');
   });


   
     data.active('active');
  
  }.bind(this);
  

  this.addTab=function(title, active, model, template){
    var nt=new tabViewModel(title, active, model, template);
 this.tabsArr.push(nt);
    this.makeTabActive(nt);
  }.bind(this);


Only difference is that now there is new parameter inside tab model constructor -the model.
Here we sending the widget that will reside in the tab .

Changing templates
Also templates for tabs must be changed for be able to support model parameter:






Adding functions to each of the widgets:
Each widget must be able now to connect with tabs widget and with other 'brother' widgets inside tabs:

//for add the search tab
homeViewModel.prototype.openSearchTab=function(){
   tabs.tabsArr.push(new tabViewModel('search','' ,new searchViewModel(),'searchTmpl'))
};
//for add the person tab
searchViewModel.prototype.openPersonTab=function(data){

   var f=data.firstname;
   var l=data.lastname;
   var newPerson=new personViewModel(f,l);
   tabs.addTab(f+' '+l,'' ,newPerson,'personTmpl');
};
//for make new friend to appear the home tab
personViewModel.prototype.addFriend=function(){
   var homeVM=tabs.tabsArr()[0].model();
   homeVM.friends.push({name:this.firstname()})
}


Thats it, now our tabbed social network application is ready and functioning.
Hope you enjoy to read this post...
download source
demo

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...