Javascript Chaining Methods

Posted on

What is chaining?

Below is an example of chaining methods, in terms of javascript this may look familiar to jQuery

var myTemplateString = myTemplate.addH1('Every page should have a h1 tag.').addH2('a h2 tag is also important').addP('and finally a p tag….').render();

The example above is of a template builder, what this is doing is building up a html string and rendering it. The advantages of chaining is that you can write all your logic in one expression, instead of creating a lot of variables to save the steps of the process.

var addH1 = myTemplate.addH1('Every page should have a h1 tag.')

var addH2 = addH2('a h2 tag is also important')

var addH2 = addP('and finally a p tag….')

var renderedTemplate = render()

Much cleaner on one line isn’t it!

So the main trick here is to use a variable in the function to save the state, and with each function that you wish to chin make sure you return this. See the bolo example

var TemplateBuilder = function() {

    return {

        currentTemplateString: '',

        addH1: function (content) {

            this.currentTemplateString += '<h1>' + content + '</h1>'
            return this

        },

        addH2: function (content) {

            this.currentTemplateString += '<h2>' + content + '</h2>'

            return this

        },

        addP: function (content) {

            this.currentTemplateString += '<p>' + content + '</p>'
            return this

        },

        render: function () {

            return this.currentTemplateString
        }

    }

}  

Notice how each function except the render function returns this. This means that the addH1() return the TemplateBuilder which contains the function addH2 which returns etc etc

var myTemplate = TemplateBuilder()

myTemplate.addH1('Every page should have a h1 tag.').addH2('a h2 tag is also important').addP('and finally a p tag....');

if (true) {

    myTemplate.addP('this was put here because true === true')

}

document.getElementById('my-paragraph').innerHTML = myTemplate.render()