jQuery Tutorial Tutorials - jQuery Chaining

jQuery Chaining

jQuery provides a powerful feature: Chaining is a common pattern which means you can chain multiple actions in a single statement on the same element.It looks like this:

$('selector').addClass().show();

each method in jQuery will return the object (selector).So there is no need to get the same selector more than once.

use jQuery functions without chaining, we have to filter the element many times.

Try now

use jQuery functions with chaining,calling multiple functions on the same object consecutively.

Try now

Implementing Method Chaining Examples

In order to gain a further understanding on chaining, you can write a object chaining:

// 1. define an object
var obj = {_color:'red',_size:'10'};
// 2. setColor action,return this for chaining
obj.setColor = function(color){
    this._color = color;
    return this;
}
obj.setSize = function(size){
    this._size = size;
    return this;
}

// call the method using chaining
console.log(obj);
obj.setColor('red').setSize('20');
console.log(obj);
obj.setSize('30').setColor('green');
console.log(obj);

Write a Class Chaining Example Step by Step:

  1. define a class with some functions to call
var Person = function(name,gender,height,weight){
    this.name = name;
    this.gender=gender;
    this.height = height;
    this.weight = weight;
}
Person.prototype.setName = function(name){
    this.name = name;
}
Person.prototype.setGender = function(gender){
    this.gender = gender;
}
Person.prototype.setHeight = function(height){
    this.height = height;
}
Person.prototype.setWeight = function(weight){
    this.weight = weight;
}
  1. Create a instance of Person and call its methods independently.
  var jacky = new Person();
  jacky.setName('Jacky');
  jacky.setGender('male');
  jacky.setHeight(180);
  jacky.setWeight(80);
  console.log(jacky);

As we can see, we have some of repetition. Method Chaining is designed to get rid of this.But this won't work currently.

    var jacky = new Person();
    jacky.setName('Jacky').setGender('male');
    // ERROR > Uncaught TypeError: Cannot call method 'setGender' of undefined

jacky.setName('Jacky') doesn't return a value,so it's undefined. SO undefined.setGender('male') would trigger a error.

  1. return this to implement chain methods.
Person.prototype.setName = function(name){
    this.name = name;
    return this;
}
Person.prototype.setGender = function(gender){
    this.gender = gender;
    return this;
}
Person.prototype.setHeight = function(height){
    this.height = height;
    return this;
}
Person.prototype.setWeight = function(weight){
    this.weight = weight;
    return this;
}
  1. now we can use chaining methods on our class:
    jacky.setName('Jacky').setGender('male')setHeight(180).setWeight(80);
    console.log(jacky);
Date:2019-06-08 23:32:23 From:www.Lautturi.com author:Lautturi