Javascript Chaining Method Pattern

Javascript Method Chaining allows us to run multiple methods on the same element within a single statement.IMPORTANT TIPS:This way, browsers do not have to find the same element(s) more than once.Now we will see how to use method chaining when using jQuery.The following example chains together the css(), height(), css(), and width() methods.The “#main” element first changes background to red, then it set height to 200, it set text-align as center and then it it set width to 500:– Without Chaining Methodvar div = $(‘#main’);

div.css(‘background’, ‘red’);
div.height(200);
div.css(‘text-align’,’center’);
div.width(500);– With Chaining Method$(‘#main’).css(‘background’, ‘red’).height(200).css(‘text-align’,’center’).width(500);IMPORTANT TIPS:When chaining, the line of code could become quite long. So, you can format it as line breaks and indentations.Example$(‘#main’).css(‘background’, ‘red’)
.height(200)
.css(‘text-align’,’center’)
.width(500);UNDERSTANDING METHOD CHAININGNow, we will create our own chaining method:// Classvar Car = function() {
this.name = ‘Audi’;
this.color = ‘blue’;
this.speed = ’180′;
};

Car.prototype.setName = function(name) {
this.name = name;
};

Car.prototype.setColor = function(color) {
this.color = color;
};

Car.prototype.setSpeed = function(speed) {
this.speed = speed;
};

Car.prototype.save = function() {
alert( this.name + ‘ – ‘ + this.color + ‘ – ‘ + this.speed); //this is alert with inserted data
// here we can save to database
};

var c = new Car();
c.setName(‘Alto’);
c.setColor(‘black’);
c.setSpeed(’90′);
c.save();OUTPUT:This will show alert box with data.
Now, we try to call this method as chaining,var c = new Car();
c.setName(‘Alto’).setColor(‘black’).setSpeed(’90′).save();This will give error:
Uncaught TypeError: Cannot call method ‘setColor’ of undefinedIMPLEMENTING METHOD CHAININGLet’s rewrite the Car class with chain methods.// Classvar Car = function() {
this.name = ‘Audi’;
this.color = ‘blue’;
this.speed = ’180′;
};

Car.prototype.setName = function(name) {
this.name = name;
return this;
};

Car.prototype.setColor = function(color) {
this.color = color;
return this;
};

Car.prototype.setSpeed = function(speed) {
this.speed = speed;
return this;
};

Car.prototype.save = function() {
alert( this.name + ‘ – ‘ + this.color + ‘ – ‘ + this.speed); //this is alert with inserted data
// here we can save to database
return this;

};Now we will try to call method as a chainingvar c = new Car();
c.setName(‘Alto’).setColor(‘black’).setSpeed(’90′).save();OUTPUT:This will show alert box with data.For more updates visitNitish Kumar Programming Blog

News Reporter

Leave a Reply

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