Tuesday, June 11, 2013

How to Use 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.
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.


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


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


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

Friday, May 24, 2013

Use TinyMCE in Asp.Net Single Page Application (SPA) using Knockout


In one of our project, we were creating web site using Asp.Net single page application with knockout.js. We had to add TinyMCE html editor in one of my page. It took some time to make it work.
Add binding handler for tinyMce using knock out. Please see code below

ko.bindingHandlers.tinymce = {
    init: function (element, valueAccessor, allBindingsAccessor, context) {
        var options = allBindingsAccessor().tinymceOptions || {};
        var modelValue = valueAccessor();
        var value = ko.utils.unwrapObservable(valueAccessor());
        var el = $(element)
        options.theme = "advanced";
      

        // Customize Tool Bars. Remove 3 lines below if you want standard tool bar
        options.theme_advanced_buttons1 = "bold,italic,underline,separator,strikethrough,justifyleft,justifycenter,justifyright, justifyfull,separator,bullist,numlist,undo,redo,link,unlink";
        options.theme_advanced_buttons2 = "outdent,indent,separator,forecolor,backcolor,emoticons,separator,formatselect";
        options.theme_advanced_buttons3 = "";

        ////handle edits made in the editor. Updates after an undo point is reached.
        options.setup = function (ed) {
            ed.onChange.add(function (ed, l) {
                if (ko.isWriteableObservable(modelValue)) {
                    modelValue(l.content);
                }
            });
        };

        //handle destroying an editor 
        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            setTimeout(function () { $(element).tinymce().remove() }, 0)
        });

        // $(element).tinymce(options);
        setTimeout(function () {
            $(element).tinymce(options);
            //$(element).tinymce({});

        }, 1000);

        el.html(value);

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

        var el = $(element)
        var value = ko.utils.unwrapObservable(valueAccessor());
        var id = el.attr('id')

        //handle programmatic updates to the observable
        // also makes sure it doesn't update it if it's the same. 
        // otherwise, it will reload the instance, causing the cursor to jump.
        if (id !== undefined) {
            $(el).tinymce();
            var tinyM = tinyMCE.getInstanceById(id);
            if (tinyM !== undefined) {
                var content = tinyM.getContent({ format: 'raw' })
                if (content !== value) {
                    el.html(value);
                }
            }
        }
    }

};

Now you can bind any text area using data-bind of knockout and don’t forget to assign id to the element e.g. id=”txtPublished”.

<textarea data-bind="tinymce: publishNotes" id="txtPublished" style="height: 150px; width: 550px;"></textarea>

Monday, November 28, 2011

How to write jQuery plugin

Apart from offering a simple, effective, way to manage elements and various scripts, jQuery also offers a mechanism for adding methods and extra functionalities to the core module. By using this mechanism we are also allowed to create a new portion of the code and add reuse it in different pages and projects.

Write your first jQuery plugin


To write a plugin, Add new property in the jQuery.fn object where the name of the property will be the name of your plugin.
(function( $ ) {
  $.fn.myPlugin = function() {
  
    // Do your awesome plugin stuff here

  };
})( jQuery );

    
Lets start adding functionality with in your plugin and use it in web pages. In our first example, I will simply fadeout the element.
(function ($) {

    $.fn.myPlugin = function () {       

        this.fadeOut('normal');

    };
})(jQuery);


Now save the file with name “jquery-myPlugin.js” and your plugin is ready to use. Create html button and div on your page. Div will fade out on the click of the button.
<div style="border: 1px dotted gray; height: 75px; margin: auto; padding: 5px; width: 400px;">
   <div id="myDiv" style="padding: 6px; background-color: Silver;">
        I am div which need to be fade out;
    </div>
    <input id="btnFadeout" type="button" value="Fade out" />
 </div>
    
Now add jQuery script file ‘jquery-1.6.2.min.js’ and your plugin file ‘jquery-myPlugin.js’ into the page.
<script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="Scripts/jquery-myPlugin.js"></script>
<script type="text/javascript">
    $(document).ready(function () {

        $("#btnFadeout").click(function () {
            $("#myDiv").myPlugin();
        });

    });
</script>

Register the click event of the button ‘btnFadeout’ button and call plugin method for ‘myDiv’ using $("#myDiv").myPlugin(); statement.

Plugin for muliple elements


You can also write plugin which performs action on the group of element. Suppose we want to change the background color of the element on mouse over. Simply get each element and register hover event for that object. Let’s start the code for hover plugin.
(function ($) {

    $.fn.hoverElement = function () {

        this.each(function () {

            $(this).hover(
                            function () {
                                $(this).addClass('hoverTextSel');
                            },
                            function () {
                                $(this).removeClass('hoverTextSel');
                            }
                        ); // end of Hover event

        }); // end for each

    }; // end of functions

})(jQuery);
    

$(selector).each() method is used to iterate over a jQuery object, array or any collection. This example registers the hover event for the each element of jQuery object.
<div style="width: 400px; margin: auto; padding: 5px; border: 1px dotted gray;">
    <div class="hoverText">
        First Button..
    </div>
    <div class="hoverText">
        Second Button..
    </div>
    <div class="hoverText">
        Third Button..
    </div>
</div>

In the html page, create buttons using div and assign ‘hoverText’ css class.
    $(".hoverText").hoverElement();
Now it is time to call the hoverElement() method for the collection. Select elements having css class ‘hoverText’ using jQuery selector ‘$(".hoverText") and call the method.

Chainability


The beauty of the jQuery’s design is, it maintains chainability. You can perform multiple actions in one series. So to maintain the chainability in a plugin, you must make sure your plugin returns the ‘this’ keyword
 (function ($) {

    $.fn.hoverElement = function () {

      return  this.each(function () {


          $(this).hover(
                            function () {
                                   $(this).addClass('hoverTextSel');
                            },
                            function () {
                                    $(this).removeClass('hoverTextSel');
                            }
                        ); // end of Hover event

        }); // end for each

    }; // end of functions

 })(jQuery);
 
Now you can perform multiple actions in one series.
  $(".hoverText2").hoverElement().css({'color':'red'}); 


Sunday, August 28, 2011

Selectors in JQuery

JQuery provides a simple way to select single element or group of elements. You can access element by type (div, span, p), id, CSS class and attribute etc.

Basic Selector


JQuery

Example Code

Description

Action

Output

$('element')

$('blockquote').css('color','red');

it select all elements with the give tag name. in this example it will return all
<blockquote> elements in the document.




Here is example text for the first selector example.


Here is second block quote text...


$('#id')

$('#item1').css('color','red');

it select single element with the give id. if more than one element has been assigned
same id, first match result will be return.



First line inside the <span id="item1" >


Second line inside the <span id="item2" >


First line inside the <span id="item1" >



$('.class')

$('.myCss').css('color','red');

it select all the elements with given class.



First line for testing.


Second line for testing.




Basic Filters


JQuery

Example Code

Description

Action

Output

:first

$('#basicList li:first').css('background-color','yellow');

:first selects the first matched element. '#basicList li:first' selects the first
element of list.




  • Item 1

  • Item 2

  • Item 3

  • Item 4

  • Item 5

  • Item 6

  • Item 7



:last

$('#basicList li:last').css('background-color','red');

:last selects the last matched element. '#basicList li:last' selects the last element
of list.



:not(selector)

$('#basicList li:not(li:first)').css('background-color','pink');

:not(selector) selects all elements that do not match the given selector. '#basicList
li:not(li:first)' selects all element other than first element.



:even

$('#basicList li:even').css('background-color','blue');

:even selects the even elements. it uses zero-indexed. so this command will select
first, third, fifth,..... so on.



:odd

$('#basicList li:odd').css('background-color','green');

:old selects the old elements. it also uses zero-indexed. So this command will select
second, fouth, sixth,..... so on.



:eq(index)

$('#basicList li:eq(3)').css('background-color','yellow');

:eq(index) selects the element at index n with in the set. this example code will
select 4th element in the list.



:gt(index)

$('#basicList li:gt(3)').css('background-color','red');

:gt(index) select all elements at an index grater than index number for filtering.



:lt(index)

$('#basicList li:lt(3)').css('background-color','purple');

:lt(index) select all elements at an index less than index number for filtering.



Filter By Content



Jquery

Example Code

Description

Action

Output

:contains(text)

$('#p1 span:contains(too)').css('background-color','yellow');

it selects all the <span> which contains word 'too'




Text in the span 1..... Text in the span 2 too



:empty

$('#list:empty').addClass('emptyUL');

:empty return those element who does not has child elements.



UL with no childs


UL with no childs

  • Child 1

  • Child 2




:has(selector)

$('#list2 li:has(a)').css('background-color', 'red');

The expression $('li:has(a)') matches a <li> if a <a> exists anywhere among
its descendants, not just as a direct child.




:parent

$('#table1 td:parent').css('background-color', 'red');

:parent is the inverse of :empty. :parent select those who has atleast one child
element.




Cell 1



Cell 4


Child Filters

:nth-child(index/even/odd/equation)


JQuery

Example Code

Description

Action

Output

:nth-child(even)

$('#Ul2 li:nth-child(even)').css('background-color', 'red');

....



List# 1

  • Item 1

  • Item 2

  • Item 3

  • Item 4

  • Item 5

  • Item 6

  • Item 7




List# 2

  • Item 1



:nth-child(odd)

$('#Ul2 li:nth-child(odd)').css('background-color', 'blue');

...



:nth-child(n)

$('#Ul2 li:nth-child(3)').css('background-color', 'yellow');

...



:nth-child(equation)

$('#Ul2 li:nth-child(3n)').css('background-color', 'yellow');

....



:first-child

$('#Ul2 li:first-child').css('background-color', 'purple');

....



:last-child

$('#Ul2 li:last-child').css('background-color', 'brown');

....



:only-child

$('#tdChildList li:only-child').css('background-color', 'gray');

....



Attribute Filters



JQuery

Example Code

Description

Action

Output

[Attribute Name]

$('#tdAtt a[id]').css('background-color','yellow');

select the elements that has specific attribue.



Click here 1

Click here 2

Click here 3

Click here 4


[AttributeName="value"]

$('#tdAtt a[rel="2"]').css('background-color','red');

Select the elements that has specific attribute with a value exactly equal to value.



[AttributeName!="value"]

$('#tdAtt a[rel!="2"]').css('background-color','brown');

Select the elements that has specific attribute with a value not equal to value.



[AttributeName^="value"]

$('#tdAtt a[href^="http://"]').css('background-color','blue');

Selects elements that have the specified attribute with a value beginning exactly
with a given string.



[AttributeName$="value"]

$('#tdAtt a[href$=".com"]').css('background-color','gray');

Selects elements that have the specified attribute with a value ending exactly with
a given string.



[AttributeName*="value"]

$('#tdAtt a[href*="www"]').css('background-color','pink');

Selects elements that have the specified attribute with a value containing the a
given substring.



Sunday, August 1, 2010

Tuple in C# 4.0



What is a Tuple?

In Mathematics, A Tuple is a sequence of finite length. An n-tuple is a tuple with n elements. For example (2, 4, 3, 8) is a 4-tuple.

C# 4.0 introduced new data type Tuple. Tuple is not new in software engineering, but of course it is new in dot net frame work 4.0. A tuple is a simple generic data structure that holds an ordered set of items of heterogeneous types. There are two ways to instantiate Tuple By calling either the Tuple constructor or the static Tuple.Create() method.


// Instantiate using constructor
Tuple<int, string, int> t1 = new Tuple<int, string, int>(3, "Frank", 9);

// Instantiate using create method
Tuple<int, int, int> t2 = Tuple.Create(3, 5, 9);



Tuple constructor and create() method can contains maximum 8 parameters. You have to take care of the 8th parameter because it replaces another tuple object.


Simple use of Tuple


You can easily return more than one value from Method without using out or ref parameters.


public Tuple<int, int> SplitPoints(string point)
{
string[] pointList = point.Split(',');

int x = Convert.ToInt32(pointList[0]);
int y = Convert.ToInt32(pointList[1]);
return Tuple.Create<int, int>(x, y);
}


SplitPoints method split the points and returns x and y points in tuple.


Tuple<int,int> points = SplitPoints("12,14");
string msg = string.Format("X: {0}, Y: {1}", points.Item1, points.Item2);
MessageBox.Show(msg);



You can get returned values from exposed properties Item1, Item2 etc by Tuple object. Item properties of Tuple object are readonly. You can not change the value of the property.

Friday, February 5, 2010

Lambda Expression in C# 3.0



Lambda Expression is the one of the best feature of the C# 3.0. Lambda expression is same as anonymous method introduced in C# 2.0. Lambda Expression is a concise syntax to achieve the same goal as anonymous method. Now we can summarize Lambda expression in one line.

“Lambda expression is simply a Method.”

Syntax of Lambda Expression

Input Parameters => Expression/Statement Block;

Left hand side of expression contains the zero or more parameters followed by Lambda operator ‘=>’ which is read as “goes to” and right hand side contains the expression or Statement block.

A simple Lambda expression: x => x * 2

This Lambda expression is read as “x goes to x times 2”. Lambda Operator “=>” has sameprecedence as assignment “=” operator. This simple expression takes one parameter “x” and returns the value “x*2”.


Parameters Type

The parameters of the lambda expression can be explicitly or implicitly typed. For example

(int p) => p * 4; // Explicitly Typed Parameter
q => q * 4; // Implicitly Typed Parameter

Explicit typed parameter is same as parameters of method where you explicitly specified the type of parameter. In an implicit typed parameter, the type of parameter inferred from the context of lambda expression in which it occurs.

Type Inference is a new feature of c# 3.0. I will explain it in some other blog.

Use simple Lambda Expression

Here is simple example of Lambda Expression which returns a list of numbers greater than 8.

int[] numbers = {1,2,3,4,5,6,7,8,9,10 };  
var returnedList = numbers.Where(n => (n > 8));

You can also use anonymous method for returning same list.
int[] numbers = {1,2,3,4,5,6,7,8,9,10 };
var returnedList = numbers.Where(delegate(int i) { return i > 8; });

Use Statement Block in Lambda Expression


Here is simple example to write statement block in the lambda expression. This expression returns list of numbers less than 4 and greater than 8.


int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

var returnedList = numbers.Where(n =>
{
if (n < 4)
return true;
else if (n > 8)
return true;

return false;
}
);

Use Lambda with More then one Parameter


You can also write lambda which takes more than one parameters. Here is an exampleof lambda which adds two integer numbers.


delegate int AddInteger(int n1, int n2);

AddInteger addInt = (x, y) => x + y;
int result = addInt(10,4); // return 14

Use Lambda with Zero parameter

Here is an example of lambda which take no parameter and returns new Guid.
delegate Guid GetNextGuid();

GetNextGuid getNewGuid = () => (Guid.NewGuid());
Guid newguid = getNewGuid();

Use Lambda that return Nothing


You can also write lambda which returns void. Here is an example that lambda is only showing message and return nothing.


delegate void ShowMessageDelegate();

ShowMessageDelegate msgdelegate = () => MessageBox.Show("It returns nothing.");
msgdelegate();

Some Build in Delegates

Dot Net Framework 3.0 provides some build in parameterized delegate types that is “Func<t>(...)” and also provides some parameterized delegates that returns void that is “Action<T>(...)”.

Monday, February 1, 2010

Extension Method

Last Few days I was thinking how Microsoft added new method in existing classes of visual studio. I was surprised because I was creating List<> and I was showing me some LINQ methods, but when I commented “Using System.Linq” line, it was showing me default list methods.

But when is removed comments “Using System.Linq”. Now Visual Studio was showing me some Linq methods in the intelligence window.


Then I started searching on the web about it. I found new exciting feature of framework 3.0, which is “Extension Methods”. You can extend existing classes without inheritance using extension methods. There are some which you should keep in mind while writing extension method.
  1. You cannot override existing method by writing extension method.
  2. If extension method has same name as instance method then it will not called, because the priority of instance method is high. At compile time extension method has low priority.
  3. You can write extension for Properties, data Members and events.
It is very simple to write extension method. Create static class and write static extension method in this class. The “this” keyword in the parameters tells the compiler to add the extension method in the type after “this” keyword. In my example “this string” compiler adds extension method to the string class.

namespace ExtensionTest
{
public static class ExtensionOfString
{
public static bool IsNumber(this string value)
{
Regex expression =
new Regex(@"^[0-9]([\.\,][0-9]*)?$");
return expression.IsMatch(value);
}
}
}
Here is an example to use extension method. Include the namespace and call your extension method like the original method of the instance.



 using ExtensionTest;
. . . . .

string number = "4";
bool isNumber = number.IsNumber();

You can see how easy it is to write extension method in Dot net.