Search
Saturday, January 28, 2012 ..:: Home ::.. Register  Login
   Minimize

1. What language code would you like to see on our articles?

2. Are you implementing SQLXML on your applications?

3. How do you use XSLT's translations?

Submit Survey  View Results
  

 XML News Minimize

Working with the JavaScript “this” Keyword

JavaScript's "this" keyword can be a bit tricky to work with depending on the context in which it's used. When it's used with patterns such as the Prototype or Revealing Prototype patterns working with "this" can be challenging in some cases. Unlike languages such as C# or Java, "this" can change context. For example, if a Calculator object named calc calls an add() function then "this" represents the Calculator object which means you can easily access any variables defined in the object such as a variable named tax by simply using this.tax.


calc.add(2, 2); //Using "this" inside of the add() function gets you to the calc object

 

However, if add() makes a call to another function then "this" changes context and no longer represents the Calculator object. In fact, "this" will change to the window object which means you can no longer access variables defined in the Calculator object such as tax. That presents a bit of a problem that’s especially challenging if you’ve never dealt with it before.

There are several ways to handle this challenge. First, you can pass "this" as a parameter to other functions. An example of passing "this" between functions is shown next. If a Calculator object calls a clearNumbers() function then you can easily access the Calculator object's constructor variables within the function. However, once clearNumbers() calls other functions such as setVal() or setEquation(), "this" changes context. To account for the change, the code passes "this" as a parameter to each of the functions and they then use it like normal. Although this type of code works, it pollutes your function parameters in some cases and becomes a little messy to work with (at least in my opinion).

 

var Calculator = function (eq) {
    //state goes here
    this.eqCtl = document.getElementById(eq);
    this.lastNumber;
    this.equalsPressed;
    this.operatorSet;
this.tax; }; Calculator.prototype = function () { //private members var add = function (x, y) { this.eqCtl.innerHTML = x + y + this.tax; }, subtract = function (x, y) { this.eqCtl.innerHTML = x – y + this.tax; }, setVal = function (val, thisObj) { thisObj.currNumberCtl.innerHTML = val; }, setEquation = function (val, thisObj) { thisObj.eqCtl.innerHTML = val; }, //Other functions omitted for brevity
clearNumbers = function () { this.lastNumber = null; this.equalsPressed = this.operatorSet = false;

//Pass the Calculator object that called clearNumbers()
//to other functions as a parameter
setVal('0', this); setEquation('', this); }; //public members return { add: add, subtract: subtract, clearNumbers: clearNumbers }; } ();


Another technique that can be used involves JavaScript's call() function. This function can be used to invoke functions and set the context of "this" while the call is being made. For example, if you want to call a function named setVal() and preserve the current value of "this" as the call is made then you can do the following:

 

setVal.call(this, 'yourParameterValue');


The current value of "this" will be passed along automatically to the setVal() function and it can safely use this.tax in the case of a Calculator object.

The following code uses the call() function to update the code shown earlier. The clearNumbers() function uses JavaScript's call() function to invoke the setVal() and setEquation() functions and preserve the current value of "this" in the process. Notice that the setVal() and setEquation() functions no longer need the extra parameter as the functions shown earlier did and can simply use "this" to access Calculator object variables defined in the object's constructor. This simplifies the call by eliminating the need for the extra parameter and makes the code a lot cleaner.

 

var Calculator = function (eq) {
    //state goes here
    this.eqCtl = document.getElementById(eq);
    this.lastNumber;
    this.equalsPressed;
    this.operatorSet;
this.tax; }; Calculator.prototype = function () { //private members var add = function (x, y) { this.eqCtl.innerHTML = x + y + this.tax; }, subtract = function (x, y) { this.eqCtl.innerHTML = x – y + this.tax; }, setVal = function (val) { this.currNumberCtl.innerHTML = val; }, setEquation = function (val) { this.eqCtl.innerHTML = val; }, //Other functions omitted for brevity clearNumbers = function () { this.lastNumber = null; this.equalsPressed = this.operatorSet = false;



//Set context of "this" to the Calculator object that called clearNumbers()
setVal.call(this, '0'); setEquation.call(this, ''); }; //public members return { add: add, subtract: subtract, clearNumbers: clearNumbers }; } ();


Another example of where “this” gets tricky is inside of jQuery event handlers. For example, assume that an init() function is called that adds a click event to DOM elements. What if you want to get to a value of “this” representing the container Calculator object while inside of the click event handler function? The context of “this” changes to the anchor tag making it challenging. Two potential options that can be used are shown next.

The first option is to store the value of “this” as a variable outside of the click event handler function. By doing this a closure is created and you can still access the original value of “this” when the event fires:

 

Calculator.prototype = {
    //private members
    init: function() {
        //Option 1 for working with "this"
        var calcObject = this;
        $('a').click(function () {
            //Can't simply use this or $(this) 
            //since "this" represents the anchor now
            //calcObject will represent the Calculator object
            calcObject.highlight($(this));
        });
    },

    highlight: function(anchor) {
        anchor.toggleClass('highlight');
    }
};


Another option is to use an overloaded version of various jQuery event handlers such as on() to pass “this” and make it accessible through the event object:

 

Calculator.prototype = {
    //private members
    init: function() {
        //Option 2 for working with "this"
        //Pass "this" into the on() call
        $('a').on('click', { calcObject: this }, function (event) {
            //Access the original value of "this" 
            //through the event object's data property
            event.data.calcObject.highlight($(this));
        });
    },

    highlight: function(anchor) {
        anchor.toggleClass('highlight');
    }
};


Notice that “this” is assigned to an object literal property named calcObject in the on() parameters. Once the click event fires the event object passed to the callback function can be used to get to the data property which exposes the calcObject value that was passed in.

Although working with JavaScript’s “this” keyword can be challenging in some scenarios, there are several different techniques that can be used to make it easier to work with. Have any other techniques you like to use? Feel free to leave a comment and share your technique with everyone.

 

 

 

Videos on JavaScript and jQuery


If you're interested in additional information about structuring JavaScript code check out my Structuring JavaScript Code course created for PluralSight. Here's a sample from the course covering closures.

Demo - Working with Closures in JavaScript

 

A sample video from the jQuery programming course that covers using the each() function is shown next:


Demo – Using jQuery’s each() Function



 Posted by dwahlin | Permanent link to this post Wed, 28 Dec 2011 16:49:00 GMT |  Comments (5)

Using the JavaScript Prototype Property to Structure and Extend Code

There are several different patterns that can be used in JavaScript to structure code and make it more re-useable, more maintainable, and less subject to naming collisions. Patterns like the Revealing Module Pattern, Prototype Pattern, Revealing Prototype Pattern, and others can be used to structure code and avoid what I call “function spaghetti code”. One of my favorite features offered by both the Prototype and the Revealing Prototype patterns is the extensibility they provide. They’re quite flexible especially compared to the Module or Revealing Module patterns out there.

Because both patterns rely on JavaScript prototyping, functions are shared across objects instances in memory and its straightforward for users of objects following these patterns to extend or override existing functionality. If you didn’t get a chance to read my previous posts on the two prototype patterns here are some basic examples of the patterns in action:

 

Prototype Pattern Example

 

var Calculator = function (eq) {
    //state goes here     
    this.eqCtl = document.getElementById(eq);
};

Calculator.prototype = { 
    add: function (x, y) {
        this.eqCtl.innerHTML = x + y;
    },
    subtract: function (x, y) {
        this.eqCtl.innerHTML = x - y;
    } 
};


Revealing Prototype Pattern Example

 

var Calculator = function (eq) {
    //state goes here
    this.eqCtl = document.getElementById(eq);
};

Calculator.prototype = function () {
    //private members
    var add = function (x, y) {
        this.eqCtl.innerHTML = x + y;
    },
    subtract = function (x, y) {
        this.eqCtl.innerHTML = x - y; 
    };

    //public members
    return {
        add: add,
        subtract: subtract
    };
} ();

 

Looking through the two examples you can see that both patterns rely on the prototype functionality available in JavaScript. The Revealing Prototype Pattern has the added functionality of being able to define public and private members within the Calculator.

Sidebar: Some people love the public/private feature and some people think all JavaScript code should be accessible to callers (which I’ll admit can simplify debugging in some scenarios). It really depends on your background and what you want. I personally like having the Revealing Prototype Pattern’s public/private member functionality available (mainly because of my background in Java and C#) since if you’re working with editors that support Intellisense or code help you only see the functions or variables that you should call as you’re typing. It’s all personal preference though and if you’d prefer to add an underscore in front of a variable or function to mark it as private then I say go for it – to each their own.

What if you want to extend one of the Calculator objects shown above or override existing functions? When using the Prototype or Revealing Prototype patterns this is possible since they both rely on prototyping. If you’re new to prototyping here’s a quick introduction to using the prototype property and different ways it can be used in your JavaScript code.

Getting Started with JavaScript Prototyping

Prototyping allows objects to inherit, override, and extend functionality provided by other objects in a similar manner as inheritance, overriding, abstraction, and related technologies do in C#, Java, and other languages. Every object you create in JavaScript has a prototype property by default that can be accessed. To better understand prototyping, take a look at the example below. Rather than adding methods directly into the BaseCalculator constructor definition as with patterns like the Revealing Module Pattern, this example relies on separate prototype definitions to define two functions.

 

var BaseCalculator = function () {
//Define a variable unique to each instance of BaseCalculator
this.decimalDigits = 2; }; //Extend BaseCalculator using prototype BaseCalculator.prototype.add = function (x, y) { return x + y; };
BaseCalculator.prototype.subtract = function (x, y) { return x - y; };

 

This code defines a BaseCalculator object with a variable named decimalDigits in the constructor. The code then extends the BaseCalculator object using the prototype property. Two functions are added including add(x,y) and subtract(x,y). This type of definition can be simplified as shown above with the Prototype Pattern by using an object literal to define the prototype functions:

 

var BaseCalculator = function() {
    //state goes here
    this.decimalDigits = 2;
};

BaseCalculator.prototype = {
    //private members
    add: function(x, y) {
        return x + y;
    },
    subtract: function(x, y) {
        return x - y;
    }
};


Once BaseCalculator is defined you can inherit from it by doing the following:

 

var Calculator = function () {
//Define a variable unique to each instance of Calculator this.tax = 5; }; Calculator.prototype = new BaseCalculator();

 

Note that Calculator is defined with a constructor that includes a tax variable that’s unique to each object instance. The Calculator’s prototype points to a new instance of BaseCalculator() allowing Calculator to inherit the add() and subtract() functions automatically. These functions are shared between both types and not duplicated in memory as instances are created which is a nice feature provided by the prototype property. An example of creating a new Calculator object instance is shown next:

 

var calc = new Calculator();
alert(calc.add(1, 1));
//variable defined in the BaseCalculator parent object is accessible from the derived Calculator object’s constructor alert(calc.decimalDigits);

 

In the previous code, BaseCalculator’s decimalDigits variable is accessible to Calculator since a new instance of BaseCalculator was supplied to the Calculator’s prototype. If you want to disable access to parent type variables defined in the constructor you can assign BaseCalculator’s prototype to Calculator’s prototype as shown next as opposed to assigning a new BaseCalculator instance:

 

var Calculator = function () {
    this.tax= 5;
};

Calculator.prototype = BaseCalculator.prototype;


Because the BaseCalcuator’s prototype is assigned directly to Calculator’s prototype the decimalDigits variable defined in BaseCalculator will no longer be accessible if you go through a Calculator object instance. The tax variable defined in Calculator would be accessible of course. For example, the following code will throw a JavaScript error when the code tries to access decimalDigits. This is due to BaseCalculator’s constructor no longer being assigned to the Calculator prototype.

 

var calc = new Calculator();
alert(calc.add(1, 1));
alert(calc.decimalDigits);


Overriding with Prototype

If you’re using either the Prototype Pattern or Revealing Prototype Pattern to structure code in JavaScript (or any other object that relies on prototyping) you can take advantage of the prototype property to override existing functionality provided by a type. This can be useful in scenarios where a library built by a 3rd party is being used and you want to extend or override existing functionality without having to modify the library’s source code. Or, you may write code that you want other developers on your team to be able to enhance/override. An example of overriding the add() function provided in Calculator is shown next:

//Override Calculator’s add() function 
Calculator.prototype.add = function (x, y) { return x + y + this.tax; };
var calc = new Calculator(); alert(calc.add(1, 1));


This code overrides the add() function provided by BaseCalculator and modifies it to add x, y, and an instance variable named myData together. The override applies to all Calculator object instances created after the override.

There’s of course more that you can do with JavaScript prototyping so I recommend reading through this post for additional details and more advanced examples of using the prototype property.


Interested in learning more about structuring JavaScript code?

 

If you're interested in additional information about structuring JavaScript code check out my latest Pluralsight course. Here's a sample from the course covering closures and how they can be created and used.

Working with Closures in JavaScript


 Posted by dwahlin | Permanent link to this post Mon, 19 Dec 2011 19:26:46 GMT |  Comments (11)

New Pluralsight Course - Structuring JavaScript Code in HTML5 Applications

I just released a new course for Pluralsight titled Structuring JavaScript Code in HTML5 Applications that covers different techniques, strategies, and patterns that can be used when working with JavaScript to encapsulate code, provide better re-use, simplify maintenance, and take variables and functions out of the global scope. The overall goal of the course is to show developers how to convert what I call “Function Spaghetti Code” into more encapsulated and modular code. The concepts covered are important especially since many of the HTML5 APIs (canvas, geolocation, web storage, and more) rely heavily on JavaScript. What if you’re not writing HTML5 applications yet? All of the topics are still directly applicable to any JavaScript code you may be writing.

A lot of the content in the course came from lessons learned while building large and small applications for clients and samples and demos for conference talks. I’ve also had several discussions about different ways to structure JavaScript code with friends such as John Papa, Jarod Ferguson, and Spike Xavier that have influenced my overall views on working with JavaScript.  A sample video from the course is available below that covers information about how closures can be used to create containers in code. Closures are a critical component of all of the patterns discussed in the course.


Demo - Working with Closures in JavaScript



The topics covered in the Structuring JavaScript Code in HTML5 Applications course are shown next:

 
 
Additional courses that I’ve published for Pluralsight are shown below:

 Posted by dwahlin | Permanent link to this post Tue, 13 Dec 2011 04:26:00 GMT |  Comments (4)

Silverlight 5 Released with a lot of Great New Features

Silverlight5


Silverlight 5 was released today and there are a ton of great new features available in this release. You can download the Silverlight 5 tools for Visual Studio 2010 SP1 here.

One of the coolest new features is the built-in support Silverlight 5 now has for 3D. I’m doing a lot with 3D right now for a project (using Unity 3D) so this is a really exciting to me. Here’s an example of Silverlight 5 3D in action from the Babylon 3D engine page:


There’s also built-in support for new media features such as trick play which allows video to be played at different speeds with automatic pitch correction for audio, hardware decoding of H.264 media, text enhancements, new controls like the PivotViewer, and much more.

Over the years my consulting company has used Silverlight in Line of Business (LOB) scenarios quite extensively so I’m really excited about some of the new LOB features that Silverlight 5 provides. I recently wrote about several of the features so if you’re interested in more details check out the posts below:

Pete Brown provides a nice list of new features provided in Silverlight 5 that you can check out here.

 Posted by dwahlin | Permanent link to this post Fri, 09 Dec 2011 21:03:45 GMT |  Comments (3)

Reducing JavaScript Code Using jsRender Templates in HTML5 Applications

imageBack in November of 2010 I wrote a post titled Reducing Code using jQuery Templates that demonstrated how jQuery Templates could be used to reduce significant amounts of JavaScript code. Although the topics and code discussed in that post are still valid and relevant in today’s applications, things have a changed some when it comes to the future of jQuery Templates. I’ve had questions come up in the jQuery classes that we offer, at conferences, and online about the future of jQuery Templates so I thought I’d put a post together that provides updated information.

To get the full story you can read Boris Moore’s blog, but in a nutshell the jQuery UI team decided to go a different direction with client-side templates and use an alternate syntax. As a result, a new script has been released called jsRender that will ultimately replace jQuery Templates - at least that’s the current plan. I’ll review a few things mentioned in my initial post here for those that aren’t familiar with templates and then show examples of using the new jsRender functionality in an application.

Nearly every language out there uses templates in some manner to minimize the amount of code that has to be written. By using templates you can define a template structure once and use it to generate code, HTML or other formats. If you’ve created ASP.NET applications then you’re aware of how powerful and productive templates are when it comes to generating HTML output. However, what if you want to use templates on the client-side to generate HTML rather than writing a lot of JavaScript to manipulate the DOM?

Although templates have been available in jQuery for quite awhile through various plug-ins, the jsRender template framework provides a new solution that doesn’t use CSS in strange ways or require a lot of knowledge about a template language. By using it you can define HTML templates in web pages and use them to render HTML output dynamically at runtime. You can download the jsRender script along with samples from https://github.com/BorisMoore/jsrender.

Defining a Template Block

You can use client-side templates by referencing the jsRender script mentioned above and then defining a <script> block in your page with a type of text/x-jquery-tmpl as shown next:

 

<script id="OrderSummaryTemplate" type="text/x-jquery-tmpl">
<!-- Template goes here –>
</script>

 

Once the script tag is defined you can place template code inside of it. Any HTML you add into the template is output automatically once the template is rendered. Of course, adding static HTML doesn’t accomplish much so jsRender provides several tags that can be placed inside of a template to define data that should be output, perform conditional logic, iterate through items, render nested templates, plus more. The key template tags available with jsRender are shown next:

Template Tag Example Description
{{=fieldNameOrExpression}}
{{=DeliveryFee}}
Used to define data values that should be rendered in the template. Evaluates the specified property on the current data item and encodes the value.
{{=fieldNameOrExpression!}}
{{=Comments!}}
Used to define HTML markup strings that should be rendered by the template (notice that a ! character is placed at the end of the string). Evaluates the specified field on the current data item and doesn’t encode the value.
{{#if condition}}
{{#if DeliveryFee > 0}}
{{=DeliveryFee}} added to your order.
{{/if}}
Used for conditional insertion of content.
{{else}}
{{#if MainItems.length===0}}
    <tr>
        <td>No items selected</td>
    </tr>
{{else}}
<tr>
<td>Ordered items!</td>
</tr>   
{{/if}}
Used to add additional conditional logic into jsRender templates.
{{#each}}
{{#each MainItems}}
    <tr>
        <td>
            {{=mi.NumberOrdered}} ordered
at ${{=mi.Price}} per item
        </td>
    </tr>
{{/each}}
Used to iterate over a data array and render the content for each data item.
{{#each tmpl=”#NestedTemplateID”}}
<script id="movieTemplate" type="text/x-jquery-tmpl"> 
    {{#each Movies tmpl="#titleTemplate"}}
</script>

<script id="titleTemplate" type="text/x-jquery-tmpl"> 
    <tr class="title">
<td>{{=Name}}</td>
</tr> </script>
Used for composition of templates. Renders one or more nested template items within the rendered output of the parent template.

 

Rendering a Template

Once a template is defined using a <script> block you can use jsRender’s render() function to convert data into HTML based upon the template. This is done by identifying the target element that will host the content, calling its html() function (when using jQuery). and then passing the HTML that’s generated by calling the render() function. The render() function accepts the data that the template will use to generate HTML content. An example of putting all of this together is shown next. You’ll see that the OrderSummaryOutput element is located in the DOM using a jQuery selector and that its html() function is passed the output generated by a jsRender template.

 

$("#OrderSummaryOutput").html($("#OrderSummaryTemplate").render(data));

 

The data can be created locally from an object literal or retrieved from a remote service call as JSON as shown nextt:

 

$.ajax({
    dataType: 'jsonp',
    url: moviesServiceUrl,
    jsonp: '$callback',
    success: showMovies
});

// Within the callback, use .tmpl() to render the data.
function showMovies(data)
{
    // Render the template with the "movies" data and insert
    // the rendered HTML under the 'movieList' element
    $("#movieList").html($("#moviesTemplate").render(data));
}

 

jsRender in Action

A sample application that I created to demonstrate jsRender in action can be downloaded here (it’s part of the sample code available with our jQuery Web Programming training course). The sample app is an ASP.NET MVC 3 project named “Order Up” that leverages jQuery heavily and uses jsRender to display order details. An example of the output that’s rendered is shown next:

image


The template used to generated the Totals, Delivery Information, Items Ordered and Accessories Ordered sections is shown next:

 

<script id="OrderSummaryTemplate" type="text/x-jquery-tmpl">
    <table style="width:100%;">
        <tbody>             
            <tr>
                <td class="OrderHeader">Totals:</td>                    
            </tr>                    
            <tr>
                <td style="font-size:12pt;">
                    <table style="width:400px;">
                        <tr>
                            <td style="width:50%;">Sub Total:</td>
                            <td>$<span id="FinalSubTotal">{{=FinalSubTotal}}</span></td>
                        </tr>
                        <tr>
                            <td style="width:50%;">Sales Tax:</td>
                            <td>$<span id="FinalSalesTax">{{=FinalSalesTax }}</span></td>
                        </tr>
                        {{#if DeliveryFee > 0}}
                            <tr>
                                <td style="width:50%;">Delivery Fee:</td>
                                <td>$<span id="FinalDeliveryFee">{{=DeliveryFee }}</span></td>
                            </tr>
                        {{/if}}
                        <tr>
                            <td style="width:50%;">Admin Fee:</td>
                            <td>$<span id="FinalAdminFee">{{=AdminFee }}</span></td>
                        </tr>
                        <tr style="border-top:1px solid black;">
                            <td style="width:50%;font-weight:bold;">Total:</td>
                            <td>$<span id="FinalTotal">{{=FinalTotal }}</span></td>
                        </tr>   
                        <tr>
                            <td colspan="2">&nbsp;</td>
                        </tr>
                        <tr>
                            <td colspan="2">Will be charged to your credit card ending with {{=CreditCard }}</td>
                        </tr>                     
                    </table>                        
                </td>
            </tr> 
            <tr>
                <td>&nbsp;</td>
            </tr> 
            <tr>
                <td class="OrderHeader">Delivery Information</td>                    
            </tr>
            <tr>
                <td>
                    <table style="width:500px;">
                        <tr>
                            <td style="width:25%;">Deliver To:</td>
                            <td>{{=DeliveryName}}</td>
                        </tr>
                        <tr>
                            <td style="width:25%;">Address:</td>
                            <td>{{=DeliveryAddress}}</td>
                        </tr>
                        <tr>
                            <td style="width:25%;">Date and Time:</td>
                            <td>{{=DeliveryDate}} from {{=DeliveryTime}}</td>
                        </tr>                        
                    </table>                         
                    </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
            </tr>                    
            <tr>
                <td class="OrderHeader">Items Ordered</td>
            </tr> 
            {{#if MainItems.length === 0}}
                <tr>
                    <td>No items selected</td>
                </tr>
            {{else}}
                {{#each MainItems tmpl="#ItemsTemplate"}}
            {{/if}}
            <tr>
                <td>&nbsp;</td>
            </tr>   
            <tr>
                <td class="OrderHeader">Accessories Ordered</td>
            </tr> 
            {{#if AccessoryItems.length === 0}}
                <tr>
                    <td>No accessories selected</td>
                </tr>
            {{else}}
                {{#each AccessoryItems tmpl="#ItemsTemplate"}}
            {{/if}}
            <tr>
                <td>&nbsp;</td>
            </tr>                          
        </tbody>
    </table>    
</script>

<script id="ItemsTemplate" type="text/x-jquery-tmpl">
    <tr>
        <td>
            {{=Name}} - {{=NumberOrdered}} ordered at $ {{=Price}} per item
        </td>
    </tr>
</script>
 

The template is rendered to a div with an ID of OrderSummaryOutput using the following code.  The code first creates a JSON object by retrieving data from controls in a checkout wizard and then calls the the render() function provided by jsRender.

 

function LoadApprovalDiv() {
    var subTotal = parseFloat($('#SubTotal').text());
    $('#ClientSubTotal').val(subTotal.toFixed(2));
    var salesTaxRate = parseFloat($('#SalesTaxRate').val()) / 100;
    var salesTaxAmount = (subTotal * salesTaxRate) * .9;
    var deliveryFee = parseFloat($('#DeliveryFee').val());
    var adminFee = ((subTotal + salesTaxAmount + deliveryFee) * .05);
    var total = (Round(subTotal) + Round(salesTaxAmount) + Round(deliveryFee) + 
                 Round(adminFee));
    $('#ClientTotal').val(total);
    var deliveryAddress = $('#Delivery_Street').val();
    //See if they entered a suite
    if ($('#Delivery_Suite').val() != '') deliveryAddress += ', Suite ' + $('#Delivery_Suite').val();
    deliveryAddress += ' ' + $('#Delivery_City').val() + ' ' + $('#Delivery_StateID option:selected').text() + ' ' + 
                       $('#Delivery_Zip').val();
    var creditCard = $('#Payment_CreditCardNumber').val();
    var abbrCreditCard = '*' + creditCard.substring(creditCard.length - 5);

    var data= {
                   'FinalSubTotal'  : subTotal.toFixed(2),
                   'FinalSalesTax'  : salesTaxAmount.toFixed(2),
                   'FinalTotal'     : total.toFixed(2),
                   'DeliveryFee'    : deliveryFee.toFixed(2),
                   'AdminFee'       : adminFee.toFixed(2),
                   'DeliveryName'   : $('#Delivery_Name').val(),
                   'DeliveryAddress': deliveryAddress,
                   'CreditCard'     : abbrCreditCard,
                   'DeliveryDate'   : $('#Delivery_DeliveryDate').val(),
                   'DeliveryTime'   : $('#Delivery_DeliveryTime option:selected').text(),
                   'MainItems'      : GenerateData('Main'),
                   'AccessoryItems' : GenerateData('Accessory')
               };

    //jQuery template example
    $("#OrderSummaryOutput").html($("#OrderSummaryTemplate").render(data));
}


If you’re working with dynamic web applications that leverage jQuery and AJAX you’ll find that jsRender can significantly increase your productivity and eliminate a lot of code that you’d normally have to write. Although jsRender is still new (at the time this post was written anyway), it’s definitely worth looking into more. In future posts I’ll discuss a companion to jsRender called jsView that provides client-side data binding capabilities.

 

 

Logo_702D5F60[1]

If you or your company is interested in training, consulting or mentoring on jQuery, HTML5,  or .NET technologies please visit http://www.thewahlingroup.com for more information. We’ve provided training, consulting and mentoring services to some of the largest companies in the world and would enjoy sharing our knowledge and real-world lessons learned with you.

 Posted by dwahlin | Permanent link to this post Wed, 23 Nov 2011 19:11:00 GMT |  Comments (15)

Looking for more?

Browse all of the entries in the Dan Wahlin&#39;s WebLog archives

  

 Favorite Links Minimize
  

Copyright 2005 CodersOasis.com and HotMediaStudios.net   Terms Of Use  Privacy Statement
Portal engine source code is copyright 2002-2012 by DotNetNuke. All Rights Reserved