JavaScript Example Method for Easily Creating Cascading Functions

  • 2021-07-18 07:06:35
  • OfStack

1. What is a cascade function?

On one line of code, call one method after another. This technique is very common in JQuery or other JavaScript libraries.
The code is as follows:


$('#myDiv').fadeOut().html(' Handsome boy ,  Hello! ').fadeIn();

Or:


myStr1.replace('k', 'R').toUpperCase().substr(0,4); 

This kind of code allows us to read the code like reading text 1, which is not only concise, readable and easy to maintain, but also improves the development efficiency.

Then how to use it?

To use cascading functions, we must return an this object in each function (that is, the object manipulated in the following methods). Now let's start creating a cascade function:


var usresData = [
 {firstName: 'Zhang', lastName: 'San', email: '111@qq.com', id: 102},
 {firstName: 'Li', lastName: 'Si', email: '222@qq.com', id: 103},
 {firstName: 'Wang', lastName: 'Wu', email: '333@qq.com', id: 105}
];

function getCaseName(str) {
 return str.replace(/\w\S*/g, function(txt){
  return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
 })
}

Next, we define an object that contains cascading functions:


var userController = {
 currentUser = '',
 findUser = function (userEmail) {
  var arrayLength = usersData.length, i;
  for (i = arrayLength - 1; i >= 0; i--) {
   if (usersData[i].email === userEmail) {
    this.currentUser = usersData[i];
    break;
   }
  }
  return this;
 },
 formatName: function () {
  if (this.currentUser) {
   this.currentUser.fullName = getCaseName(this.currentUser.firstName) + ' ' + getCaseName(this.currentUser.lastName);
  }
  return this;
 },
 createLayout: function () {
  if (this.currentUser) {
   this.currentUser.viewData = '<h2> Member : ' + this.currentUser.fullName + '</h2>'​
   + '<p>ID: ' + this.currentUser.id + '</p>' + '<p>Email: ' + this.currentUser.email + '</p>';
  }
  return this;
 },
 displayUser: function () {
  if (!this.currentUser) return;
  $('.members-wrapper').append(this.currentUser.viewData);
 }
}

After defining the cascade function, we will call it very elegantly:


userController.findUser('111@qq.com').formatName().createLayout().displayUser();

Summarize

The above is the whole content of this article. I hope the content of this article can bring 1 certain help to everyone's study or work. If you have any questions, you can leave a message for communication.


Related articles: