jQuery Document Ready…the sequel

My previous post jQuery Document Ready, the saga continues… got me thinking. Why not write a jQuery plugin which simulates a ready handler tied to an AJAX success handler. Let me explain.

Consider test1.html, view1.html and test1.js from the previous post:
test1.html

<html>
    <head>
        <title>Document Ready Demo</title>

        <script src = "jquery-1.4.2.js"></script>
        <script src = "test1.js"></script>

        <script>
            $(document).ready(function () {
                //make sure there is no caching to avoid confusion
                $.ajaxSetup({cache: false});

                $('#fetchView1').click(function () {
                    $.get('view1.html', function (data) {
                        $('#viewText1').html(data);
                    });
                });
            });
        </script>
    </head>

    <body>
        <button id = "fetchView1">Fetch View1</button>

        <div id = "viewText1">
            View1 content goes here
        </div>
    </body>
</html>

view1.html

<div>
   <input type="text" id="inputView1" value="Click button to fill with 1111" size="50" />
   <button id="buttonView1">Fill Input with number 1111</button>
</div>

test1.js

(function($) {
   $(document).ready(function(event) {

   console.log('test1.js document.ready executed');

   $('#buttonView1').click(function() {
        console.log('buttonView1 view clicked');
        $('#inputView1').val('1111');
   });
   console.log('buttonView1 button bound now');

//possibily more processing code and bindings

   });
})(jQuery);

Like I discussed, the intent of having the document.ready is that somehow it attaches itself to view1.html. Well it attaches itself to test1.html and because of this programmers resort to using live or liverquery. Again, nothing wrong with these tools but the penalty of freedom is performance overhead.

Ideally it would be nice if we could execute the JS code on AJAX success, rather automatically. Taking a cue and inspiration from the livequery plugin this is what I came up with:

jquery.jready.js

/*!
 * jQuery plugin jReady v1.0
 * https://phptouch.com/
 *
 * Copyright 2011, Jayesh Wadhwani
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * Released under the MIT, BSD, and GPL Licenses.
 *
 * Date: 31-July-2011
 */
(function($) {
    $.fn.jready = function(jreadyId, fn) {
        var j;
        //make a jready object
        j = new $.jready(this, jreadyId, fn);
        return this;
    };
    
    //jready function. Objects are made of this
    $.jready = function(context, jreadyId, fn) {
//        this.selector = selector;
        this.jreadyId = jreadyId;
        this.context = context || document;
        this.fn = fn;
        this.id = $.jready.fns.push(this) - 1;

        return this;
    };
    
    //function prototype
    $.jready.prototype = {
        //execute attached functions
        execute: function() { 
         var that = this; 
         this.context.each(function(){
            that.fn.apply(this);   
         })
         
        }
    };

    $.extend($.jready, {
        fns: [], //jready objects collection
        //jready handler
        execute: function(event, xhr, settings) {
            //check if there is a jready id present in the url
            var match = /.+?jready=(\w+)[\?\&]?/ig.exec(settings.url);

            if (match !== null) {
                var jreadyId = match[1] || null;
                //if there is a jready toke/id present then 
                //check if in the collection and execute the handler
                //in the object
                if (jreadyId) {
                    $.each($.jready.fns, function(index, fn) {
                        if (fn.jreadyId == jreadyId) {
                            fn.execute();
                            return false;
                        };
                    });
                }
            }
        },
        //bind the global ajax success
        bind: function() { $(document).ajaxSuccess($.jready.execute); }
    });
    // //bind the global ajax success when dom is ready
    $(function() { $.jready.bind(); });
})(jQuery);

I will explain the internals of the plugin in a minute.

Using this plugin test1.js now contains:

(function($) {
   $(document).jready('view1', function(event) {
      console.log('test1.js-view1 jready executed');    
      
      $('#buttonView1').click(function(){
         console.log('buttonView1 view clicked');
         $('#inputView1').val('1111');
      });
      console.log('buttonView1 button bound now');
      //event bidings
      
      //processing code
      
   });
})(jQuery);

Finally test1.html now contains:

<html>
    <head>
        <title>Document Ready Demo</title>

        <script src = "jquery-1.4.2.js"></script>
        <script src = "jquery.jready.js"></script>
        <script src = "test1.js"></script>

        <script>
            $(document).ready(function () {
                //make sure there is no caching to avoid confusion
                $.ajaxSetup({cache: false});

                $('#fetchView1').click(function () {
                    $.get('view1.html?jready=view1', function (data) {
                        $('#viewText1').html(data);
                    });
                });
            });
        </script>
    </head>

    <body>
        <button id = "fetchView1">Fetch View1</button>

        <div id = "viewText1">
            View1 content goes here
        </div>
    </body>
</html>

If I now run test1.html, no binding takes place. It only takes place when the AJAX call completes. Let me explain how that happens.

1. In the URL I have attached an identifying token, ‘view1.html?jready=view1. This token can be any alpha-numeric characters.

2. In test1.js I have replaced $(document).ready(function(event) with $(document).jready(‘view1’, function(event) . Note that the “event type” here is identical to the identifying token in the URL

3. When $(document).jready(‘view1’, function(event) is executed, all the plugin does is to store away the handler function in a function object which in turn is stored in an array.

4. Also note that the global handler ajaxSuccess at the end of the plugin code. The function attached to this event checks for a valid identifying token. If a valid token is detected then it iterates over all function objects looking for a match. If a match is found then it executes the jready handler.

I still have to work on the plugin, particularly in the area of error handling. But for now it should be enough to get you going.

Elementary I believe:-)

Happy Computing!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s