State Pattern in JavaScript

In recent coding I encounter a situation that in different contexts, the button’s action should change accordingly. In other words, the page has several states, and in different states, the action of a same button should be different. I know in Java we have State Pattern in hand to deal with this situation, which take the advantage of Java’s OO features like inheritance and polymorphism. I don’t want to use JavaScript’s class which would definitely raise the complexity of the codes. With the help of the realization of Strategy Pattern in Book JavaScript Patterns, I write something like this.

Say, we have two buttons in the page, which are add and del. SPAGE is the namespace.

var SPAGE = {
    btn: {},  //collection of all btn's click event handlers
          //it has different states
              //in this example there are two buttons: add, del

    states:{ //state set of btn
        full: {}, //state 1: full
        half: {}  //state 2: half
    },

    setState: function(s){ //switch state
                  this.btn = this.states[s];
              }
}

SPAGE.states.full = (function(){ //realize event handlers of state 'full'
    var add = function(){
        print('full add click');
    }
    var del = function(){
        print('full delete click');
    }
    return {
        add: add,
        del: del
    }

})();
SPAGE.states.half = (function(){ //realize the methods of state 'half'
    var add = function(){
        print('half add click');
    }
    var del = function(){
        print('half delete click');
    }
    return {
        add: add,
        del: del
    }
})();

//set state and call
SPAGE.setState('full');
SPAGE.btn.add();    //click the button add
                    //output: full add click
SPAGE.setState('half');
SPAGE.btn.del();    //click the button del
                    //output: half delete click

So, I think I take advantages of JavaScript’s nice features of objects. I don’t know how you guys solve the similar situation. Any discussion is welcomed warmly~:)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>