11/27/13

starting with Mongodb

Is it complicate to start using MongoDB?
 -Not at all
All you need is
1. Download the latest version of Mongo (i prefer 64-bit for windows)
2. Extract it on some place on your machine (like C:\mongodb)
3. Create a directory where you want your database to be (like C:\mongodb\data\db)

Now, go to Run >cmd and type :
1. cd C:\mongodb\bin\
2. mongod.exe --dbpath "C:\mongodb\data\db"
Now mongoDB console must start:
Anjoy!

11/25/13

Starting with gitHub

What are you need to start  use github?
Not much...
1. Install github client (for windows)
2. after installing go to AllPrograms >GitHub > git shell
3. git console should appear.
Now, after you have git installed, lets start with some basic operations:
To get the code from remote repository to local:
1. browse to some directory where you want your local repository to be

2. type: git clone https://github.com/someuser/YOUR_REPO_NAME.git
If all the things is correct - the local repository with all its contents should create.

Congratulation! you just became a git user

11/24/13

Startnig with Nodejs

Nodejs is very light but powerfull server which uses javascript as serverside language. Installation is free and very easy:
1. go to downloads page
2. choose installer compatible with your system type (i prefer MSI installer)
3. (to determine  in windows right click on "my computer" > system type)
4.after short installation  Allprograms->Node.js
Choose nodejs command prompt. type: node ---version
If all the things correct you will get something like this:
Congratulation!!!
You have Installed Node.js





10/23/13

Shortened text directive - angularjs

 In this artricle we will try to create angularjs directive which  will display only first 10 characters of element text and link  that opens the whole text when user clicked on it.

Before clicking: 

After clicking: 


To simplify the example i'm using the code of angular phonecat tuttorial.
In the example we need to display the snippet  property of phone object

html markup:
 
    
 
Directive declaration:
 
/* app\js\directives.js */
var phonecatDirectives = angular.module('phonecatDirectives', []);
phonecatDirectives.directive('zippy', function () { 
    
    return {
      restrict: "E",
      replace: true,
      transclude: false,
      scope: { title:'@zippyTitle' },
      template: '
{{title}}
' , // The linking function will add behavior to the template link: function(scope, element, attrs) { var opened=true; scope.$watch('title',function(newVal, oldVal){ element.html(scope.title.substr(0,10)+' ...'); // Title element var title = angular.element(element.children()[0]), // Opened / closed state opened = true; // Clicking on title should open/close the zippy title.on('click', toggle); }) // Toggle the closed/opened state function toggle() { if(opened) element.text(scope.title) opened = !opened; //element.removeClass(opened ? 'closed' : 'opened'); //element.addClass(opened ? 'opened' : 'closed'); } } }; });

6/26/13

Testing our widget with unit tests

Why to write tests?
When developing something, it is good practice to check after each change if your code still working correctly, doing the things you want it to do.
As the code becomes more complicate, the quantity of cases to check became larger, and more difficult to complete all of them without forget something.
That's where unit tests came to help us. Jquery-ui works with Qunit unit tests, so we will use this framework too.
When you write your unit test you must think about which behavior you want to be tested.
Lets list some behaviors we want our loading indicator widget to behave:
1. after initialization, loading widget should add a div styled with 'loading' class.
2. The loading div should been removed after widget destroyed.


Writing tests

When you write a test you need to specify 3 things:
1. to set up the initial conditions the test will begin with
2. to Specify what result you expect
3. to check if the result is as expected
Lets test the first behavior
   
module( "loadingindicator: core" );

test( "the loading element appears", function() {
 expect( 1 );
 var element = $( "#main" ).loadingindicator();
 ok( $( "#main .loading" ).length, 1 );

});
Explanation: in this test we applying the plugin on the "main" div element (located on the testing environment) and after this we checking if some element decorated with class element appears inside the "main" after plugin code activated.
After running the tests in Qunit testing environment, if everything is working as expected (acording to the plan) - we get the following screen with blue lines:

4/9/13

creating jquery-ui plugin -part2

In this post we will extend the plugin created in previous post, so it will became more customizable.

Firstly lets speak about options.
Options like parameters which supplied to the plugin when it initiated.
Lets make the user to be able of customizing the text of loading message:
     $.widget( "ui.loadingindicator", {       
        options: {
          caption: "loading..."
        },
     ...
Explanation: Here we specifying the caption parameter (the message text), which value by default is "loading...", but user may change it if plugin initiated following way:
$( "#main" ).loadingindicator({caption:'wait please'});

Another thing we can extend our plugin is to add to it some public methods.
Lets add close method  which will make the 'loading' message disappear after the process finished:
   //public
    close: function(){
          this._destroy();
    },
   //private
   _destroy: function(){
          this.element.find(".loading").remove();
   },
Explanation:
$.widget factory makes methods without '_' prefix to be accessible from within plugin calls. From now you may hide the indicator by writing following code:
$( "#main" ).loadingindicator('close');
One more thing that you can see almost in each jquery-ui plugin is events.
Events are fired by plugin when some actions occurred. The plugin's user can specify callbacks, which will take place in response of the event.
Lets add some event to our plugin:
 //click event and callback
  var that = this;     
  this._on( this.loadingDiv, {
   click: function( event ) {
     that._trigger( "click", event, {caption:that.options.caption});     
   }     
 })
Now, if user want something to happen when loading message being clicked he can subscribe to the event when plugin initiated:
var lodaing=$( "#main" ).loadingindicator({
 caption:'wait please',
 click: function(event ,ui ){
   //will close the message
   lodaing.loadingindicator('close');
 }  
});

demo

4/8/13

creating loadingindicator jquery ui plugin

In this post i will show you how easily  you can create your own plugin (or widget) with little help of jquery ui utils.

Because i'm a great jquery-ui fan - i will try to do things  (as much as i can) in a jquery-ui style.
You can download the whole  jqueryui project from the github (click on ZIP button) and play with it.

After extracting all the files you can see demos directory -where you can find demos of all existing widgets.
All the widgets code can be found inside  UI directory.
Lets create our own widget- jquery.ui.loadingindicator.js. This widget will make some animation indicating that some  process (like ajax request) being started:
(function($) {
     $.widget("ui.loadingindicator", {
  
    _create: function() {
           var el = this.element,
           loadingDiv = $('<div />',{class:"loading"}).text('loading...');
           

           el.append(loadingDiv);
           
         //locate in the center of parent
           var left = el.width() / 2 - loadingDiv.width() / 2;
           var top = el.height() / 2 - loadingDiv.height() / 2; 
           loadingDiv.css({ left: left + 'px', top: top + 'px' });     
   }
 })
})(jQuery);

Explanation:
I'm using here the jquery ui $.widget factory - method that give me the ability to create a widget from the template - the widget already have base methods like _create or _init, all i need is to override them and put in some logic.
All the widget makes is to create a simple div with caption "loading" and locate it in the center of parent element (the element that widget is applied on) .

We will create the special css for our widget:
ltes create   jquery.ui.loadingindicator.css
inside themes/base directory
Important!
for the future use you must add following code
 @import url("jquery.ui.loadingindicator.css");
at the and of jquery.ui.base.css
It will help you to create the demo

jquery.ui.loadingindicator.css :
.loading{
  background:#030303;
  width:100px;
  text-align:center;
  height:30px;
  position:absolute;
  border-radius: 4px;
        -webkit-border-radius: 4px ;
        -moz-border-radius: 4px ;
         padding-top:12px;
         color:#fff;
   
 /*for continous glowing animation*/
        -webkit-animation-name:             glow; 
        -webkit-animation-duration:         3s; 
        -webkit-animation-iteration-count:  infinite;
        -webkit-transition-timing-function: linear;
        -webkit-animation-timing: cubic-bezier(0.1, 0.2, 0.8, 0.9);
}
 
@-webkit-keyframes glow {
  0%{     -webkit-box-shadow: 0px 0px 15px 0px rgba(0, 0, 190, .75);   }
  50% {     -webkit-box-shadow: 0px 0px 15px 5px rgba(0,0, 190, .75);   }   
  100% {     -webkit-box-shadow: 0px 0px 15px 0px rgba(0,0, 190, .75);   }
}

This css styles the 'loading' message and adds the css3 glow animation to it.
 To see how the newly maiden things working we will create our demo inside demos directory
Lets create default.html
and put it inside demos/loadingindicator folder

 
 jQuery UI Loading indicator - Default functionality
 
 
 
 

 
 
 
 




 Now we have a nice "loading" indication message that resides in the middle of parent div.
In the future posts we will extend this base widget functionality
Thank you for reading so far...

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

Dynamic tabs with knockoutjs - part 2

Creating 3 simple different widgets
In this post we will create a 3 simple widgets which will be hosted inside the tabs.

Home widget
This widget shows the friends collection, and able to open search page.
Model:

var homeViewModel=function(){  
  this.typename='home';    
  this.templName='homeTmpl';
  this.friends=ko.observableArray([{name:'Shlomo'}]) 
};
View:

<script id="homeTmpl" type="text/html">
 <h3>
  wellcome to Social Network!</h3>
 <b>friends: </b> <hr/>
   <ul data-bind="foreach:friends">
   <li data-bind="text:name"></li> </ul> <div> Wanna find more friends? <button data-bind="click:openSearchTab"
>click here</button><
 /div> </script> <!--ko template: { name: 'homeTmpl' }--><!--/ko-->
demo
Search widget
This widet must show the search engine:
To simplify the functionality, our search may find only to persons:
Vasia and Kolia

Model:

var searchViewModel=function(){
  
  this.typename='search';  
  var that=this;
  this.results=ko.observableArray([]);
  this.searchterm=ko.observable();

  this.clickSearch=function(){
  
    this.results([]);//empty the results array 
    switch(that.searchterm()){   
      case 'k':
        this.results.push({firstname:'Kostia',lastname:'Baranov'});
        break;
      case 'v':    
        this.results.push({firstname:'Vasia',lastname:'Kozlov'});
        break;
   default :
     this.results.push({firstname:'Vasia',lastname:'Kozlov'});
  this.results.push({firstname:'Kostia',lastname:'Baranov'});
    }
  };
  
  
  this.templName='searchTmpl';
};

View:

  <script id="searchTmpl" type="text/html">
    <div data-bind="text:typename">
    </div>
    <input data-bind="value:searchterm" />
    <button class="o" data-bind="click:clickSearch">press</button>

    <table data-bind="foreach:results" class="results">
      <tr>
        <td data-bind="text:firstname,click:$parent.openPersonTab"></td>
      </tr>
    </table>
    </div>
  </script>

demo
Person widget
This widget must show the person details and be able to add this person to friends
array:

Model:


var personViewModel=function(firstname,lastname){
  var that=this;
  this.firstname=ko.observable(firstname);
  this.lastname=ko.observable(lastname);


  this.templName="personTmpl";  
}
View:


  <script id="personTmpl" type="text/html">
    <section class="person"> <img src="img/placeholder.png" alt="pic" />
      <div> <b>first name:</b>
        <label data-bind="text:firstname"></label>
      </div>
      <div> <b>last name:</b>
        <label data-bind="text:lastname"></label>
      </div>
      <button data-bind="click:addFriend">add as friend</button>
    </section>
  </script>
  <!--ko template: { name: 'personTmpl', data: person }-->
  <!--/ko-->
demo
you can download source from github
Now that all 'insider' widgets are ready - we can proceed to the next step

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

Dynamic tabs with knockoutjs - introduction

There is many beautifull javascript tabs-widget examples across the web, many of them fit perfectly for the regular scenarios of displaying static or dynamic content. When talking about dynamic content - it usually means that objects which showed in each tab is from the same type, only the quantity of tabs may vary. (like this example - each tab must have the same structure of header and content).
In this post i will demonstrate how to create tabs widget where each tab is represent a different kind of javascript module, which act independently and in coexistence with other tabs-modules.



i decided to divide this post to 4 parts (so it will be more convenient to read) 
introduction - the Social Netwok app 
part 1 - create a simple tabs widget with knockoutjs (next post)
part 2 - create  3 viewModels for each kind of tabs (next next post)
part 3 - get all the stuff to work together (next next next post)

So here is the first part:


the Social Netwok app - the spec
Lest say we want to create social network, with 'search-firends' page, 'display person details' page and 'home' page, only instead of pages - each view will be displayed on different tab panel:
home:

search:

person details:
To achieve this goal we will need to define 3 kind of different javascript functionalities - one for each page/tab:  'Search' -must be able to perform the  persons search, 'home' -must display the friends list, and 'person details' -must display details of person and to add this person to the friend list which appears on the 'home' page.
Expect of acting independently each functionality must at the same time to connect with other 'brothers' (like add person to friends list)   and to connect with the tabs widget - (like open search view inside tab).

Note that in some cases tabs should be able to contain multiple instances of objects from same type- like two persons...

I hope you enjoyed reading this post so far
so if you want to continue - here is the next part 

3/17/13

How to extend jquery ui widget

Sometimes it is happen that you need to use some jquery ui widget, which is perfect solution for your project except one little feature - that must be somehow act differently. In that case some customization of the widget needed. As you may already know - in javascript, it may be plenty of ways to do the same thing, the question is - what is the nicest way. In this post i will try to show some ways of widget customization and discus the advantages/disadvantages of each way.

For example we will take the jquery ui dialog widget. Lets say in your project you must have the same  dialogs as jquery ui offers, but without the titlebar :

Of course, in real life the things to change would be much more interesting and complicate, the dialog titlebar is only using us for making the example easier.
So, you can handle this in some quick way like using the "open" event of the plugin:

$( "#dialog" ).dialog({
    modal:true,
    open:function(){
       $(this).parent().find(".ui-dialog-titlebar").hide();
    }
}) 

This will work, but what if we using the same kind of dialog in multiple places? In this case you will need to specify the same open handler code each time you make use the of dialog widget.
More convenient way to make all dialog insitances to hide titlebar at once- is to make a little modifictaion inside the code of the widget.
You can download the full source code of all jquery ui widgets from the githube repository and play with the code as you wish. Once you clicked the ZIP button

all the code is yours. You can find the dialog widget code inside ui folder -here is it jquery.ui.widget.js.
So desired functionality can easily be achieved if we comment out the following line inside _create method:



var uiDialogTitlebar = (self.uiDialogTitlebar = $('<div>
</div>'))

 .addClass(
  'ui-dialog-titlebar ' +
  'ui-widget-header ' +
  'ui-corner-all ' +
  'ui-helper-clearfix'
 )
 /*.prependTo(uiDialog)*/,

This code creating the titlebar element and adds it to dialog body.
Comment it out will make all the dialogs to appear without titlebars in all the places, as needed.
Unfortunately, short time after the brilliant solution you found it may occur that the application design will change so that in some lonely case the dialog titlebar will be still needed.

extending dialog widget
For this case, i think  you may take advantage of the $.widget method generously offered by jquery-ui framework.The method give you an ability to create your own custom dialog widget that inherits form the standart jquery-ui module:



$.widget('ui.extendeddialog', $.ui.dialog, {
 _init: function() {
  if ( this.options.autoOpen ) {
   this.open();
  }
  //hiding the titlebar  
         this.uiDialogTitlebar.hide();
 }
});     

Explanation: In this code i make the new widget named extendeddialog, which is exact copy of jquery-ui dialog except -that it has no titlebar. I choose to override the _init method that runs after all the elements of the widget been created already in previously called _create method.
Now if you need to display dialogs without titlebars you may use the new extended widget ,which should called in  following way:


$( "#dialog" ).extendeddialog();

The original dialog widget is functioning now without changes.
$( "#dialog1" ).dialog();

You may be noticed the code inside init method that does not contribute a thing to hiding titlebar functionality:

if ( this.options.autoOpen ) {
 this.open();
}
This code must stay inside the _init method because we overriding it when we specify it inside $.widget function parameter. So here is the way the widget extending code may be more nice: instead of coping all the code of overriden function - we may call the original function of the original widget (prototype) from inside the overriding code:

$.widget('ui.extendeddialog', $.ui.dialog, {
  _init: function() {
    //calling the _init function of prototype  (like "super" in java)
    $.ui.dialog.prototype._init.call(this);
    //hiding the titlebar
    this.uiDialogTitlebar.hide();
  }
});
Now it much more nice.
We can augment our new extendeddialog widget even little bit more: We can add the ability to hide the titlebar conditionally(depend on hideTitle custom option):

 $.widget('ui.extendeddialog', $.ui.dialog, {
 _init: function() { 
  $.ui.dialog.prototype._init.call(this);
  if( this.options.hideTitle )this.uiDialogTitlebar.hide();
 },
        //extending the options
 options : {
              hideTitle:true 
 }
});
From now if we give hideTitle option the false value( by default it is true) - the titlebar will become visible.

$( "#dialog" ).extendeddialog({hideTitle:false});
Hope this post was interesting,
I wish it will help somebody to  understand things better...

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