RSS

Use Jquery command chaining pattern in your own javascript objects

16 Sep

Fluent APIs are really easy and popular(eg. LINQ, JQuery) in programming world because it makes your code more readable and provides really flexible programming pattern. If you write your own javascript for various needs you can easily achive this sort of fluent API pattern relatively easy with chaining sort of pattern.

      var MyLib = MyLib || {};

        MyLib.Calculator = function(initVal) {

            var calcResult = initVal;

            var context = this; // make sure 'this' is not modified by API users for correct usage in closure functions
            this.add = function(x) {
                calcResult = calcResult + x;
                return context;
            };


            this.subtract = function(x) {
                calcResult = calcResult - x;
                return context;
            };

            this.multiply = function(x) {
                calcResult = calcResult * x;
                return context;
            };
            this.divide = function(x) {
                calcResult = calcResult / x;
                return context;
            };

            this.displayResult = function(callback) {

                callback(calcResult);
                return context;

            };

      

           
        };

        //using calculator

        new MyLib.Calculator(5).add(10).multiply(2).divide(2).displayResult(function (result) { console.log(result);});


This is sort of a method chaining pattern. When you call math operation on calculator class it is returning the calculator object it self while keeping the result for next calls.

Advertisements
 
Leave a comment

Posted by on September 16, 2012 in Javascript

 

Tags:

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

 
%d bloggers like this: