Search
Wednesday, February 08, 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

jQuery Tip #1 – Defining a Context When Using Selectors

I really enjoy working with jQuery and have had the opportunity to use it a lot over the years on various projects.  It’s an essential part of my “technology tool belt”. My company has also started providing new training classes on jQuery to various companies and I’ve had a lot of great questions come up about best practices, tips and tricks, when certain functions should be used over other functions, and more.

I decided to put together a series of posts that highlight simple tips and tricks that I’ve used in jQuery applications over the years to provide some guidance to developers new to jQuery and provide answers to different questions I’ve been asked. In this first post I’ll cover an oldie but goodie tip – defining a context when using selectors. It’s something I struggled with when I first started using jQuery but once I found the secret (which is quite easy) it changed how I used selectors and how I used CSS classes in my HTML.

Defining a Context when using Selectors

Selectors are an essential part of jQuery that provide a great way to locate nodes in the DOM quickly and easily. For example, the following selector can be used to find all div elements with a class of panel on them in a page:

var panelDivs = $('div.panel'); 


Selectors are well documented at http://api.jquery.com/category/selectors so I won't rehash what they are or how to use them here. However, I do want to mention one simple yet powerful tip that many people new to jQuery will find useful. It's one of the tips that I've ended up using over and over as I build applications. To demonstrate the technique let’s walk through a simple example.

Selectors can be used in the following way to find all elements with a class of panel on them:


var panels = $('.panel');


However, what if you want to grab all elements with a panel class that are children of a given parent container element? To better understand the scenario, consider the following HTML:

<div id="emailContainer">
    <div class="panel">
        
</div> <div class="panel">
</div> </div> <div id="ordersContainer"> <div class="panel">
</div> <div class="panel">
</div> </div>


Assume that you already have a reference to the emailContainer div stored in a variable named emailDiv:

var emailDiv = $('#emailContainer');


How do you find all div elements with a panel class on them within the emailDiv element as opposed to finding every one within the page? One technique is to use the jQuery find() function:

var panels = emailDiv.find('div.panel');


You can alternatively supply a context object to the selector as shown next. This is the technique I normally use mainly because it’s something I’ve used for quite awhile (and old habits are hard to break).

var panels = $('div.panel', emailDiv);


Which way is the best? It depends on who you talk to although you can check out some live performance tests at http://jsperf.com/jquery-find-vs-context-sel that infer that find() has a slight performance advantage. Regardless, knowing how to supply a context when using selectors is a great technique to understand and useful in many different scenarios.

My development team has been using this technique a lot in an application that has several panels with a consistent set of CSS classes defined on elements within each panel. We’re using a plugin that we need to dynamically re-size as the panel changes size and created a function called refreshPanel() that accepts the panel to refresh. The object passed in to the function is used as the context for several selectors (it’s a jQuery object) to identify a starting point for searching elements with specific CSS classes. Here’s a section of a JavaScript file that defines refreshPanel().

 

...
refreshPanel = function (panel) { var padding = 5; //Handle height if (panelHeight == null) { toolbarH = $('.toolBar', panel).height(); tableHeadH = $('.clientDataTable', panel).height(); maxHeight = $(window).height(); panelHeight = (maxHeight / panels.length) - toolbarH - (tableHeadH * 2); } //Grab panel's current height var h = panel.height() - toolbarH - (tableHeadH * 2); //If panel's height is greater than the original panelHeight assigned in "if" above then they're maximizing var newHeight = (h > panelHeight) ? maxHeight - toolbarH - (tableHeadH * 2) : panelHeight; var w = panel.width(); $('div.dataTables_scrollBody', panel).height(newHeight - padding).width(w); $('.dataTables_scrollHeadInner, table.clientDataTable', panel).width(w); }
...


Notice that the panel object is used throughout as the selector context which allows the function to be re-used over and over for multiple panels. We use this technique in several places which allows us to consistently use the same CSS classes over and over within a given panel.


Conclusion

This is the first tip in a series I’ll be writing about jQuery. Although this tip is simple (and hopefully something you already know about if you’re an experienced jQuery developer), it’s very useful in many real-world situations.

 

 
If you’re interested in learning more about jQuery or JavaScript check out my jQuery Fundamentals or Structuring JavaScript Code courses from Pluralsight. We also offer onsite/online training options as well at http://www.thewahlingroup.com.

 Posted by dwahlin | Permanent link to this post Wed, 08 Feb 2012 07:06:00 GMT |  Comments (1)

Upcoming ASP.NET, HTML5 and Windows 8 Talks and Workshops at DevConnections 2012

It’s that time of the year again! DevConnections 2012 is right around the corner and we have a lot of great new workshops and sessions planned for the ASP.NET and Client-Dev (HTML5, Windows 8 Metro, JavaScript, jQuery, etc.) tracks.

The keynote at DevConnections will be given by the one and only Scott Guthrie who’s always up to something cool and is a lot of fun to listen to.

image

Several other great speakers will be at the conference as well. Here’s a quick sampling:

image

And of course there are many more! Sessions are only part of a conference experience. Yeah there are the parties too … but the real value is in the hallway conversations and the people you meet and continue to talk to beyond the conference event. DevConnections is a great place to strike up these conversations as its one of the largest gatherings of super experts in our industry … and they are all very approachable. There will also be a panel discussions with many of us, which is a great chance to put us on the spot.

Thanks to John for letting me hijack that last paragraph along with the pictures he put on his blog. I thought he nailed what DevConnections is all about in just a few sentences.

I’ll be co-presenting a full day jQuery workshop with John on Monday, March 26th. We really enjoy co-presenting and have a lot of great jQuery topics to discuss. You do have to register for the workshops so make sure to do that when you register for the conference.

image

Workshop

APR02: Building Ajax-Enabled Applications with jQuery (9:00AM - 4:00PM)
Add'l Fee $399.00
John Papa & Dan Wahlin

Building cross-browser AJAX applications can be a fun yet challenging proposition. In this workshop, you’ll learn how to put the joy back into AJAX development using the jQuery script library. Learn how jQuery selectors can reduce code and simplify the process of finding DOM elements, how chaining can be used to accomplish multiple tasks with a single line of code and how cross-browser AJAX calls can be made using built-in jQuery functionality. Other topics covered include using client-side templates as well as built-in plugins. If you’ve wanted to learn jQuery but haven’t made the time, this is the workshop for you since we’ll take you from the ground floor all the way to the top.

 

Sessions

I’m also presenting or co-presenting 4 other sessions. If you’ll be at the conference please stop by and introduce yourself.

image

CWI202: Fundamentals of Windows 8 HTML/JavaScript Metro Style Apps
Dan Wahlin

Heard the buzz about Windows 8 Metro style applications but don’t know where to start? In this session, you’ll learn how your existing HTML, JavaScript, and CSS skills can be used to build Windows 8 Metro applications. Learn about different Visual Studio 11 project templates, built-in scripts, and Windows Runtime (WinRT) calls that you can make to build robust applications that will be capable of targeting millions of Windows users on the desktop and on tablets in the near future.

CHT201: Developing an HTML5/jQuery Application - End to End
Dan Wahlin

HTML5 is all the rage these days but where do you look to find robust examples of using it along with jQuery, jQuery templates, Ajax calls, data access technologies, and more? In this session, Dan Wahlin will walk through an application called Account at a Glance that demonstrates how key HTML5 technologies can be integrated and used to present data to users in different ways. Topics covered include exposing data to the client using Entity Framework Code First and RESTful services, using jQuery templates to render data, JavaScript techniques for structuring code, the role of HTML5 semantic tags, as well as how technologies such as the canvas, SVG, and video can be used. If you want to learn HTML5 techniques and strategies from a real app, then this session is for you.

CJS301: Techniques, Strategies, and Patterns for Structuring JavaScript Code
John Papa & Dan Wahlin

Are you writing a lot of JavaScript code and trying to apply good practices to make it more maintainable and flexible? In this session, learn about common practices to make avoid problems such as polluting the global namespace and code that executes inconsistently, by using patterns such as separation and the Revealing Module Pattern. You will leave this session with several tips on how to write clean, more maintainable, and consistent code.

<shamelessPlug>

If you can’t make the conference make sure to check out my new Structuring JavaScript Code course at Pluralsight.com. If you’re still writing “function spaghetti code” I’ll show you several techniques/patterns that will really improve the re-use and maintainability of your code.Good stuff to know if you’re building Web applications.

</shamelessPlug>

CJS202: Templating and Data Binding for HTML5 Applications with JsRender and JsViews
John Papa & Dan Wahlin

Interested in using the latest JavaScript libraries for templating and data binding your HTML5 app? In this session you will learn how to simplify JavaScript development using JsRender and JsViews (the replacements for jQuery templates). Learn how JsRender brings a new templating library to HTML5 development that has a code-less tag syntax, high performance, no dependency on jQuery nor a DOM, supports creating custom functions, and uses pure string-based rendering. You will also see how JsViews compliments JsRender by providing data binding features through observability of changes that work with plain old JavaScript objects (POJO).

 Posted by dwahlin | Permanent link to this post Sun, 05 Feb 2012 00:15:00 GMT |  Comments (2)

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 (13)

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 (5)

Looking for more?

Browse all of the entries in the Dan Wahlin'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