.NET Discussion

.NET Issues, Problems, Code Samples, and Fixes

Javascript: How To Implement Callback Functionality

I know I haven’t posted for a while, so for all 1 of my loyal readers (ha, kidding. Friend.), I apologize. Mostly the reason why is that I’ve been super busy (a good thing)! Anyways, this isn’t a personal blog, so I’ll spare you the details and get down to business.

As you may well know from my previous few posts, I’ve been dipping my toes into the jQuery and Javascript world for quite some time now. I actually learned jQuery first before I had any real experience with Javascript (yes, that’s how freakishly easy it is to learn and use), so a lot of what jQuery did I took for granted: DOM manipulation, event binding, and, as mentioned in the title of this post, callbacks. If you’re not TOTALLY familiar with how Javascript works (don’t worry, it took me a while, too), digest this:

In static languages such as VB.NET or C#, a variable at its most basic level contains an instance of an object, such as a String object or an instantiated class of some sort. In dynamic languages (e.g., Javascript), not only can variables house objects (which may or may not be instantiated), but they can store functions as well. As in, the whole function itself. This function can be anonymous or a predefined named function. For instance:

var myFunction = function () { 
    //do work here 
};

Which, depending on how it’s referenced, can do two different things. Let’s say you have a function called callingFunction() that needs to pass a parameter of some sort. Using the myFunction() example above as the parameter, calling callingFunction(myFunction()) and callingFunction(myFunction) do two different things.

callingFunction(myFunction()) passes the value returned by myFunction as the parameter, which means that myFunction must first run before callingFunction does so that it may pass along its result. If myFunction returns, say, the number 2, this is effectively the same as calling callingFunction(2). (Assuming that myFunction has no other functionality than doing some work and returning a number. If myFunction does anything else, it will run before callingFunction, as described.)

callingFunction(myFunction) passes the function myFunction to be used at a later time by callingFunction. This means the function being passed along as a parameter has not run yet. This is how callback functionality is created. Essentially, once callingFunction has successfully run, a typical control flow would be to run the callback function passed along (after checking if one exists). This is convenient (and more dynamic than, well, static languages) because you don’t have to hard-code which functionality occurs after a certain process finishes. You can just pass in whatever functionality you want, which leads to the beauty of anonymous functions. Example:

function callingFunction(someFunction) {
    var someVar;
    //do some work here
    //after work is done:
    if (someFunction != null) {
        someFunction(someVar);
    }
}

Viola! Callback functionality.

In jQuery, if you want to add click handler functionality, it’s as simple as $('.myClass').click(function() { //some work });. That function() is just an anonymous (nameless) function passed along to dictate the functionality that must happen once your selector has been clicked. The beauty of jQuery is in its abstraction. You don’t have to try to wire up the actual event listeners for the clicking of the mouse, you just tell jQuery what to do after the mouse has clicked on your selector.

IMHO, this couldn’t be any easier. As a newbie, it took me a while to wrap my head around it, but I hope that these examples may help someone save a bit of time trying to figure this out.

Advertisements

December 21, 2009 Posted by | Javascript, jquery, Tips & Tricks | 3 Comments

Simple jQuery Expand/Contract Functionality

I can’t express enough how much learning jQuery has expanded my ability to simply and dynamically add amazing effects very easily to my User Interfaces. Maybe I should start a jQuery blog? 🙂

One feature I come across a lot is the ability to expand and contract a section of the page, say a <div>. Before when I wanted to do this, I had to resort to either adding markup to my code and importing huge function-specific script files (ie, all they did was perform the expand/contract) or rely on ASP.NET’s AjaxToolkit’s Collapsible Panel Extender. While these solutions… worked… I was never really comfortable using them, and they were hardly reusable or scalable. Enter jQuery.

Let’s say I have a bit of HTML that is like so:

<p class="toggle">Expand/Collapse</p>
<div>
    <p>Some text goes here!</p>
</div>
<p class="toggle">Expand/Collapse</p>
<div>
    <p>Some more text goes here!</p>
</div>

If you wanted the ability to show/hide that following div, the jQuery is ridiculously simple:

$(document).ready(function() {
    $(".toggle").click(function () {
        $(this).next("div").slideToggle("fast");
    });
});

Yes, literally that’s it. So long as you keep with the HTML convention above, that’s all the jQuery you would need. You don’t have to add any extra markup or link one ID to another or anything. It’s all done via jQuery, and pretty much in one line ($(this).next("div").slideToggle("fast");).

Of course, sometimes you may want to do more. For instance, what if you wanted to change the text of the toggle button? Assume now that “Expand/Collapse” now reads “View Additional Info”. Here’s your jQuery:

$(document).ready(function() {
    $(".toggle").toggle(function () {
        $(this).text("Hide Additional Info")
        $(this).next("div").slideDown("fast");
        }, function() {
        $(this).text("View Additional Info")
        $(this).next("div").slideUp("fast");        
    });
});

Extremely simple, elegant, and even intuitive! If you ever doubted jQuery’s power before, you may want to reconsider. I sure did.

July 31, 2009 Posted by | jquery, Tips & Tricks | , | 3 Comments

jQuery: Awesome

Back in the day, I discovered jQuery, but never really did anything with it. I always wanted to learn, but really never had the time. I do now. Let me tell you something:

jQuery is friggin awesome.

Let me preface with the fact that I know little to no JavaScript. I once wrote one function to add the current date to a textbox in JS and it took me around half the day. However, in that same amount of time about two weeks ago, I was able to nearly completely understand how jQuery works. After a week, I was helping out others with their problems.

Don’t get me wrong, jQuery can’t do everything, but it sure can do some powerful stuff. For instance, AJAX is a breeze. For one project I had to make an AJAX call to check to see if someone was posting a comment as someone else while logged in as themselves, so I had to write my AJAX function myself. It took me 53 lines of JS and maybe 3 days to get it working right (along with a TON of research). When I wanted to apply that same function to my new project, I thought I would give jQuery a chance.

Eight lines of code. Actually, technically one line of code because I broke it into several lines:

function MakeCall(url,doAsync,callback) {
$.ajax({
url: url,
async: doAsync,
dataType: "text",
success: callback
});
}

Of course I have to handle the “callback” in the function that’s calling the MakeCall() function, but the actual making the call has been reduced by 85%. And it’s easier to maintain and reuse! This isn’t all that jQuery is good for. I believe jQuery’s strongest feature is its document manipulation. If you want to change something, all you have to do is select the element or class and, well, change it. For instance, if you have a div with an id of “myDiv”, to change the CSS class on it, you just do:

$("#myDiv").addClass("someClass");

Really, that’s it. If you wanted to do that when something is clicked, you could do:

$("#myLink").click(function () { $("#myDiv").addClass("someClass"); });

No, for real. That’s all you have to do. You can also manipulate things on page load:

$.(document).ready( function () { //run functions here });

The last and I think one of the most important aspects of jQuery is that it is VERY well documented, VERY ardently followed, and VERY well supported. You can even get Intellisense in Visual Studio 2008! I couldn’t possibly go through all the cool stuff that jQuery can do. You’ll have to see for yourself. It truly is amazing, and it is, as I was told, “brain-dead-stupid easy to learn”.

June 12, 2009 Posted by | AJAX, CSS, Javascript, jquery, Tips & Tricks, Visual Studio.NET | 1 Comment