tester
tester

Reputation: 23189

Converting a javascript library to chain methods

var Stuff = (function() {
    return {
        getId: function (id) {
            return document.getElementById(id);
        },
        attr: function (ele, attr, newVal) {
            var newVal = newVal || null;
            if (newVal) {
                ele.setAttribute(attr, newVal);
            } else {
                var attrs = ele.attributes,
                attrslen = attrs.length,
                result = ele.getAttribute(attr) || ele[attr] || null;

                if (!result) {
                    for (var i = 0; i < attrslen; i++)
                        if (attr[i].nodeName === attr) result = attr[i].nodeValue;
                }
                return result;
            }
        }
    }
})();

With this html:

<div id="foo" data-stuff="XYZ">Test Div</div>

The current implementation:

(function ($) {
    console.log(
        $.attr($.getId('foo'), 'data-stuff') // XYZ
    );
})(Stuff);

How do I rewrite my library above to make it chain like the following?

(function ($) {
    console.log(
        $.getId('foo').attr('data-stuff') // XYZ
    );  
})(Stuff);

Upvotes: 2

Views: 416

Answers (1)

user113716
user113716

Reputation: 322562

Building specifically from your code, you could do this:

Example: http://jsfiddle.net/patrick_dw/MbZ33/

var Stuff = (function() {
    return {
        elem:null,
        getId: function (id) {
            this.elem = document.getElementById(id);
            return this;
        },
        attr: function (attr, newVal) {
            var newVal = newVal || null;
            var ele = this.elem;
            if (newVal) {
                ele.setAttribute(attr, newVal);
            } else {
                var attrs = ele.attributes,
                attrslen = attrs.length,
                result = ele.getAttribute(attr) || ele[attr] || null;

                if (!result) {
                    for (var i = 0; i < attrslen; i++)
                        if (attr[i].nodeName === attr) result = attr[i].nodeValue;
                }
                return result;
            }
        }
    }
})();

This adds a elem property which stores the result of the getId. The getId returns this, which is the object referenced by Stuff containing all the methods. As such, you can directly call attr from the returned object.

I would imagine you would want to include a return value for attr of this for when the attribute is being set, so that chaining can continue.

Upvotes: 2

Related Questions