Last Updated: February 25, 2016
·
1.099K
· davidcollingwood

Do you even code? [jQuery Object Creation]

jQuery is a brilliant framework that simplifies interaction with the DOM significantly, and one of the most common things you will find yourself doing is creating jQuery objects like: $("div"). This performance test shows just how much time we are actually sacrificing for the convenience of using jQuery, and what we want to avoid is creating an excess of jQuery objects.

The problem occurs when you want to use a jQuery object multiple times and the usual way of doing this is to create a variable which references the jQuery object, and for a lot of people this works and they are quite happy with it. I was never entirely satisfied with this solution, so one day I created a custom "use" function that works with any jQuery object. You run your selector once and then use the "this" keyword to refer to it. No more extra variables to keep track of and as a bonus it makes it super easy to see at a glance which code is affecting which parts of the DOM.

Now I know there are developers out there who aren't so keen on using the "this" keyword in these situations, so this solution won't be for everyone, but it works for me and I'm sure it will be of use to many other coders out there too.

Here is another performance test which compares creating multiple jQuery objects, to using the custom "use" function. As expected if you create a jQuery object twice then you get twice the speed, three equals three times the speed, four equals four, etc.

You can check out the code here: https://github.com/davidcollingwood/do-you-even-code

A Simple Example

$("div").use(function() {
    this.find("p").addClass("paragraph");
    this.addClass("example").show();
});

From Within a Click handler

$("div").click(function() {
    $(this).use(function() {
        this.find("p").removeClass("paragraph");
        this.removeClass("example").hide();
    });
});

Using the Optional Argument

$("div").use(function(that) {
    this.find("p").addClass("paragraph");

    this.click(function() {
        that.removeClass("example").hide();
    });

    this.addClass("example").show();
});

1 Response
Add your response

Nice utility, good to see patterns like this :)

over 1 year ago ·