Search code examples
javascriptjquerychaining

Using Jquery (or even just Javascript), how to chain commands together


There are several functions in jquery which you can do the following: $('#element').each().get('title').othercmd()

How can I create a class ( or a series of classes ) to replicate this behavior? Basically, I want to something like this:

test = new Something()
test.generateSection('title').addData('somedata')

What is correct for this?

Thanks


Solution

  • One approach is to return "this" (the object) in each function. So you could do something like this:

    <script>
    var Something = function() {
      this.hi = function() {
        alert('hi');
        return this;
      };
      this.bye = function() {
        alert('bye');
        return this;
      };
    }
    var myObj = new Something();
    myObj.hi().bye();
    </script>