Method Chaining

Method Chaining is one of the coolest aspects of jQuery. Method chaining will allow you to string multiple methods together to achieve more than one function in one line of code. This is because most jQuery methods return a jQuery object that can then be used to call another method, allowing you and the browser to not have to find the object each time your code needs to perform an action with the object.

  <script type="text/javascript">
    $(function () {
      $("#divName").css("font-family", "verdana").css("font-size", "10pt").css("color", "green").text("This is a test div");
    });

  </script>
  <div id="divName"></div>

This example gets the object <div id="divName"></div> and applies three css methods and one text method to it.

You could achieve the same result with the following, but it would be slower, and in the context of a large project, this is not the correct way to do it:

  <script type="text/javascript">
    $(function () {
      $("#divName").css("font-family", "verdana");
      $("#divName").css("font-size", "10pt");
      $("#divName").css("font-weight", "bold");
      $("#divName").css("color", "green")
      $("#divName").text("This is a test div");
    });

  </script>
  <div id="divName"></div>

This example gets the object <div id="divName"></div> four separate times and applies each method to it individually, and is not efficient coding. It will work in the same way as the previous example, but will be slower to execute.

jQuery isn’t picky with spacing and/or formatting of code. As long as the code syntax is correct, you can add in any lines and spaces that will make your code easier for you to read.

You can do something like this with your code to make your method chaining easier for you to read:

  <script type="text/javascript">
    $(function () {
      $("#divName")
.css("font-family", "verdana")
        .css("font-size", "10pt")
          .css("font-weight", "bold")
            .css("color", "green")
              .text("This is a test div");
    });

  </script>
  <div id="divName"></div>

All extra lines and spaces are ignored as if they don’t exist.

Important Note: Some jQuery methods don’t return a jQuery object, so method chaining won’t be possible with them. Others, like the text() method used in the above examples, only return the jQuery object if you pass parameters to it. If you leave the parameter out, it will return the text contained in the original returned object. More on this in later chapters.



No comments:

Post a Comment