Knockout UI: Datepicker

Introduction

Knockout UI is a series of articles, I will talk about it in the next articles, and it is a combination of knockoutjs custom binding with jquery ui components. This article will show you how to do this combination.

knockout ui datepicker
Combination knockoutjs custom binding with jqueryui datepicker

Knockout UI Datepicker

In this sample I had choose jqueryui datepciker to combine it with ko custom binding. You can use ui datepicker in the same way what you used to use before, but without calling it many times.

Usage

If you have in your application many jqueryui datepickers; it’s better to do it’s implementation in one place instead repeating it many times in your project, in that case you can change the datepicker component from one place, and you can pass the same parameter what you used to pass, but without calling the widget many time.

Create the following files:

  1. viewModel.js.
  2. koDatepicker.js.
  3. index.html.

In viewModel.js do the following:


var viewModel = {
 dateOptions:{
     dateFormat:"d MM, y"
 }
}; 

In koDatepicker.js do the following


ko.bindingHandlers.koDatepicker = {
 init: function(element, valueAccessor, allBindingsAccessor) {
     var options = {
             showOtherMonths: true,
             selectOtherMonths: true
     };

     if (typeof valueAccessor() === 'object') {
             $.extend(options, valueAccessor());
     }

     $(element).datepicker(options);
 }
};

Required Files:

first of all you have to import the files in the same sequence:

  1. Jquery.js
  2. jqueryui.js
  3. jqueryui.css
  4. knockoutjs
  5. koDatepicker.js
  6. viewModel.js

 

After importing your libraries and required files; you have to calling the component in the HTML File.

In index.html add the following:

<input type="text" data-bind="datepicker: dateOptions" />

So your custom binding you can reusing it in any project, and you can pass the dateOptions from any viewModel you have.

Hint: you can add your default date options in your custom binding, and the specified options from the date options in the viewModel.

 

Demos

About these ads

One thought on “Knockout UI: Datepicker

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s