Click here to Skip to main content
15,881,588 members
Articles / Programming Languages / Javascript

How to Use jQuery Methods with Knockout

Rate me:
Please Sign up or sign in to vote.
5.00/5 (5 votes)
12 Jun 2013CPOL1 min read 31.8K   10   2
Using jQuery methods with Knockout.

Knockout out provides a sophisticated way to use jQuery methods with your binding. You can use a custom binding feature provided by knockout for this purpose. Suppose I want to use SlideDown and slideUp methods of jQuery to show and hide the elements. Although it can be achieve by using the “visible” property of knockout, but I want to do it in a fancy way.

Add a sub property in ko.bindingHandlers and write your custom code in init and update method. This blog does not explain how to create custom binding. You can find its help in the knockout documentation. Here is the complete code of the custom binding for show/hide element using jQuery.

JavaScript
ko.bindingHandlers.collapseVisible = {
  
 init: function (element, valueAccessor) {

   var value = valueAccessor();
   $(element).toggle(ko.utils.unwrapObservable(value));
   // Use "unwrapObservable" so we can
   // handle values that may or may not be observable

 },
 
 update: function (element, valueAccessor, allBindingsAccessor) {

   var value = valueAccessor();
   var allBindings = allBindingsAccessor();

   // Grab some more data from another binding property
   var duration = allBindings.slideDuration || 500; 

   ko.utils.unwrapObservable(value) ? $(element).slideDown(duration) : $(element).slideUp(duration);

  }
};

In the init method set the initial state of the element. This method calls once for each DOM element. Get element using $(element) and perform action which you want.

Whenever the associated observable change, the ko calls you update callback method. In this example I get the value of element using ko.utils.unwrapObservable(value) and call slideUp or slideDown method according to value.

Now next step is to bind your DOM element using ‘CollapseVisible’ custom binding.

XML
<div data-bind="collapseVisible: displayDetail, slideDuration: 1000" class="desc">
    Lorem Ipsum is simply dummy text of the ...
</div>

So whenever the value of displayDetail observable will change. The Update callback method will be called and according to value the slideUp and slideDown methods will be called.

Complete Solution

Now here is complete working solution for it. Set style for your element.

<script src="Scripts/jquery-2.0.0.js"></script>
 <script src="Scripts/knockout-2.2.1.js"></script>

 <style>
     .box
     {
       border: 1px black solid; width: 650px; margin-left: auto; margin-right: auto;
     }

     .box .title
     {
       padding: 8px; background-color: #e1e1e1; border-bottom: 1px black solid;
     }

     .box .title .showButton
     {
       float: right;
     }

     .box .desc
     {
       padding: 8px;font-size:12px;
     }
 
 </style>

Set your element, assign CSS classes and set binding etc.

XML
<div class="box">
    <div class="title">

       <span data-bind="html: title"></span>
       <a class="showButton" href="#" 
         data-bind="html: showButtonText, event: { click: onShow }"></a>
    </div>
    <div data-bind="collapseVisible: displayDetail, slideDuration: 1000" class="desc">
         Lorem Ipsum is simply dummy...
    </div>
</div>

Finally create your view model, custom binding and bind them to your page.

JavaScript
<script type="text/javascript">

   var vm = {

      title: "Collapsible   Box",

      showButtonText: ko.observable('Show'),

      displayDetail: ko.observable(false),

      onShow: function () {

          var newVal = !this.displayDetail();


          this.displayDetail(newVal);
          this.showButtonText(newVal ? "Hide" : "Show");
      }
   };

   ko.bindingHandlers.collapseVisible = {
            
        init: function (element, valueAccessor) {

             var value = valueAccessor();
             $(element).toggle(ko.utils.unwrapObservable(value));
             // Use "unwrapObservable" so we can handle 
             // values that may or may not be observable

            },            
        update: function (element, valueAccessor, allBindingsAccessor) {

                var value = valueAccessor();
                var allBindings = allBindingsAccessor();

                // Grab some more data from another binding property
                var duration = allBindings.slideDuration || 500; 

                ko.utils.unwrapObservable(value) ? 
                  $(element).slideDown(duration) : $(element).slideUp(duration);
            }
   };

   ko.applyBindings(vm);

</script>
This article was originally posted at http://shakeel-dot-net.blogspot.com/feeds/posts/default

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Chief Technology Officer
Pakistan Pakistan
Passion and positive dedication is essential part of success. I believe on hardworking and sharing knowledge with others. I always try to be a better than I am and think positive for positive result.

My Blogs

My Linked-In Profile

Comments and Discussions

 
QuestionUse jQuery Methods with Knockout Foreach Method Pin
Hamed_Farag12-Aug-13 21:49
Hamed_Farag12-Aug-13 21:49 
AnswerRe: Use jQuery Methods with Knockout Foreach Method Pin
Shakeel Iqbal13-Aug-13 2:07
Shakeel Iqbal13-Aug-13 2:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.