views:

53

answers:

1

Hi I've been playing around trying to recreate the way in which jQuery chains it's functions for it's "select" then "do" behaviour.

Note: I don't want to chain functions with jQuery, I want to chain them like jQuery.

So based on the jQuery code what I have so far is (doesn't work in IE):

var x = function(string) {
    return new x.fn.init(string);
};

x.fn = x.prototype = {

    message: '',

    init: function(string) {
        x.fn.message = string;
    },

    log: function() {
       console.log(x.fn.message);    
    }
};

x.fn.init.prototype = x.fn;

var start = function() {    
    x('hello world').log();
};

document.addEventListener('DOMContentLoaded', start, false);

The code works but when I watch '$' in jQuery "fn" & "prototype" show up as being "jQuery()" but in my code when I watch "x": "fn" and "prototype" are both shown as objects containing "message", "init" and "log" and in both cases "init" contains "prototype" which contains my three functions again and the nesting continues seemingly infinitely...

I'm clearly missing something here. What are they doing in differently in jQuery to prevent this endless loop.

To be honest I'm struggling to get my head around this stuff as well so if anyone has a link to some good reading around this that would be much appreciated too.

A: 

All you should need to do is return this; from the method invocations that you want to be able to chain from. Of course - that's dependent on this correctly referencing the appropriate target.

Matt Ball
True but do I not then lose the ability to namespace my functions?
Mattyod
I'm not exactly sure what you mean. The functions will be defined on the object you're returning, not the global namespace. Or are you saying that `return this;` will expose all your private functions as well?
Matt Ball
At any rate, if you want to see how jQuery chaining actually works, check out the uncompressed [jQuery source code](http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js).
Matt Ball
Yup the example above is indeed based on the method used in jQuery. Unless I'm miss understanding you; my point earlier was that if I simply return "this" from the function "x" then the function "log" needs to be at the same level as it and cannot be protected by a namespace is in my example. No?
Mattyod
Correct. But if you want to be able to chain `log` calls, why would you protect it?
Matt Ball
To avoid conflicts?
Mattyod