html JS-方法-chaining.html

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html JS-方法-chaining.html相关的知识,希望对你有一定的参考价值。

 // The data store:
 var usersData = [
  {firstName:"tommy", lastName:"MalCom", email:"test@test.com", id:102},
  {firstName:"Peter", lastName:"brecHt", email:"test2@test2.com", id:103},
  {firstName:"RoHan", lastName:"sahu", email:"test3@test3.com", id:104}
 ];

 function titleCaseName(str)
 {
  return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
 }
 // Our object with the chainable methods
 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;
    }
   }

   //console.log(this);    
   return this;
    
    
  },
  formatName:function () {
   if (this.currentUser) {
    this.currentUser.fullName = titleCaseName (this.currentUser.firstName + " " + 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);

  }
 };
       
       // Now, use the chaninable methods with expressiveness:


    userController.findUser("test3@test3.com").formatName().createLayout().displayUser();


/*
same as

    userController.findUser("test3@test3.com")
    .formatName()
    .createLayout()
    .displayUser()



same as
    userController.findUser("test3@test3.com");
    userController.formatName();
    userController.createLayout();
    userController.displayUser();
*/
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="js method chaining" />
<script src="http://code.jquery.com/jquery-latest.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <div class="members-wrapper"></div>
  <div class="logger"></div>
  
   <script>
    
</script>
 
</body>
   
</html>  

以上是关于html JS-方法-chaining.html的主要内容,如果未能解决你的问题,请参考以下文章

一个js方法中怎么调用另一个js文件

怎样用js方法过滤html等代码

一个js方法中怎么调用另一个js文件

UIWebView中Html中用JS调用OC方法及OC执行JS代码

跪求解答js的问题,动态添加的html元素怎么调用js方法?

如何在js文件中调用另一个js中的方法(详细请进)