Underscore.js (JavaScript Object manipulation method)

Source: Internet
Author: User
Tags script tag hosting

The underscore encapsulates common JavaScript object manipulation methods for improved development efficiency. (underscore can also be used in the node. JS Runtime environment.) )

Before you learn underscore, you should save its API address, because you will often visit it later:

Http://documentcloud.github.com/underscore/

As you can see from the API, underscore does not have any complex structures and processes, it simply provides a series of commonly used functions. If you use the method from the API to the beginning, you will know it very well.

Nevertheless, I think it is necessary to take some important approaches to discuss with you, they are very important, but in the API is not clear enough to describe.

5.1 Underscore object Encapsulation

Underscore does not extend in the native JavaScript object prototype, but, like jquery, encapsulates the data in a custom object (hereinafter referred to as "underscore object").

You can get native JavaScript data by invoking the value () method of a underscore object, for example:

JS Code
    1. Defining a JavaScript built-in object
    2. var jsdata = {
    3. Name: ' data '
    4. }
    5. Create an object as a underscore object with the _ () method
    6. The prototype of the Underscoredata object contains all the methods defined in the underscore, which you can use arbitrarily
    7. var Underscoredata = _ (Jsdata);
    8. The raw data is obtained through the value method, i.e. Jsdata
    9. Underscoredata.value ();

5.2 Priority calls to JavaScript 1.6 built-in methods

There are many methods in underscore that have been incorporated into the specification in JavaScript1.6, so the built-in methods provided by the hosting environment are prioritized within the underscore object (if the hosting environment has already implemented these methods), thereby increasing the efficiency of the function execution.

For host environments that do not support JavaScript 1.6, underscore is implemented in its own way, which is completely transparent to developers.

The hosting environment described here may be the node. JS runtime Environment, or the client browser.

5.3 Changing the namespace

Underscore uses _ (underscore) to access and create objects by default, but the name may not conform to our naming conventions or cause naming conflicts.

We can use the Noconflict () method to change the name of the underscore and restore the value before the _ (underscore) variable, for example:

JS Code
  1. <script type="Text/javascript" >
  2. var _ = ' Custom variable ';
  3. </script>
  4. <script type="Text/javascript" src="underscore/underscore-min.js" ></script>
  5. <script type="Text/javascript" >
  6. //Underscore object
  7. Console.dir (_);
  8. //Rename the underscore object to us, followed by us to access and create the underscore object
  9. var us = _.noconflict ();
  10. //output "Custom variable"
  11. Console.dir (_);
  12. </script>

5.4 Chain operation

Remember how we did the linking operation in jquery? For example:

JS Code
    1. $ (' a ')
    2. . css (' position ', ' relative ')
    3. . attr (' href ', ' # ')
    4. . Show ();

Underscore also supports chained operations, but you need to call the chain () method first to declare it:

JS Code
    1. var arr = [10, 20, 30];
    2. _ (ARR)
    3. . Chain ()
    4. . Map (function (item) { return item++;})
    5. . First ()
    6. . value ();

If the chain () method is called, underscore wraps the called method inside a closure and encapsulates the return value as a underscore object and returns:

JS Code
    1. This is a key function in underscore that implements chained operations, encapsulates the return value as a new underscore object, and calls the chain () method again, providing support for the next function in the method chain.
    2. var result = function (obj, chain) {
    3. return chain _ (obj). Chain (): obj;
    4. }

5.5 Extension Underscore

We can easily extend the custom method to underscore with the mixin () method, for example:

JS Code
    1. _.mixin ({
    2. Method1: function (object) {
    3. //Todo
    4. },
    5. METHOD2: function (arr) {
    6. //Todo
    7. },
    8. METHOD3: function (fn) {
    9. //Todo
    10. }
    11. });

These methods are appended to the underscore prototype object, and all created underscore objects can use these methods, and they enjoy the same environment as other methods.

5.6 Iterating through the collection

The each () and map () methods are the two most commonly used methods used to iterate over a collection (an array or an object) and sequentially process each element in the collection, for example:

JS Code
    1. var arr = [1, 2, 3];
    2. _ (ARR). Map (function (item, i) {
    3. Arr[i] = Item + 1;
    4. });
    5. var obj = {
    6. First:1,
    7. Second:2
    8. }
    9. _ (obj). each (function (value, key) {
    10. return Obj[key] = value + 1;
    11. });

The map () method has the same function as the each () method, but it records the result returned by each iteration function to a new array and returns.

5.7 Function throttling

function throttling is the control of a function's execution frequency or interval (just like the gate that controls the flow of water), underscore provides the debounce () and throttle () Two methods for function throttling.

To describe these two methods more clearly, let's say we need to implement two requirements:

Requirement 1: When the user enters search criteria in the text box, automatically queries the matching keywords and prompts the user (as if entering search keywords in Tmall)

First, we analyze the 1th requirement, we can bind the KeyPress event of the text box, and when the input box contents change, the query matches the keyword and shows. Let's say I want to query "Windows Phone", which contains 13 characters, and I'm typing it takes only 1 seconds (as if it's a bit fast, meaning it), then in these 1 seconds, 13 query methods are called. This is a very scary thing, and if Tmall is done this way, I'm afraid it will hang up before Singles Day arrives (of course, it's not so fragile, but it's definitely not the best solution)

A better way is if we want the user to have entered the completion, or are waiting for a prompt (perhaps he is too lazy to input the following), then query the matching keyword.

Finally we found that in both cases we expected the user to temporarily stop the input, so we decided to wait for the user to pause the input for 200 milliseconds before the query (if the user is constantly entering the content, then we think he may be very clear about the keyword he wants, so we will prompt him again)

At this point, using the Debounce () function in underscore, we can easily implement this requirement:

JS Code
    1. <input type="text" id="search" name="search"/>
    2. <script type="Text/javascript" >
    3. var query = _ (function () {
    4. //query operation here
    5. }). debounce (200);
    6. $ (' #search '). Bind (' keypress ', query);
    7. </script>

As you can see, our code is very concise, throttling control has been implemented in the Debounce () method, and we only tell it that when the query function has not been called within 200 milliseconds, it executes our query operation and then binds the query function to the KeyPress event of the input box.

How does the query function come from? When we call the Debounce () method, we pass a function that executes the query and a time (in milliseconds), and the Debounce () method throttles the function based on the time we passed and returns a new function (that is, the query function). We can safely invoke the query function, and the Debounce () method will help us to control it as required.

Requirement 2: Call the server interface to check for new content when the user drags the browser scroll bar

To analyze the 2nd requirement, we can bind the query method to the Window.onscroll event, but this is obviously not a good practice, because a user dragging a scroll bar can trigger dozens of or even hundreds of onscroll events.

Can we use the Debounce () method above for throttling control? When the user has finished dragging the scroll bar, then query the new content? But this does not match the requirements, and the user wants to see changes in the new content as they drag.

So we decided to do this: when the user drags, the interval of every two queries is not less than 500 milliseconds, and if the user drags for 1 seconds, this may trigger 200 onscroll events, but we only make 2 queries at most.

Using the throttle () method in underscore, we can also easily implement this requirement:

JS Code
    1. <script type="Text/javascript" >
    2. var query = _ (function () {
    3. //query operation here
    4. }). Throttle (500);
    5. $ (window). Bind (' scroll ', query);
    6. </script>

The code is still very concise, because within the throttle () method, all the controls that have been implemented for us.

You may have found that the debounce () and throttle () Two methods are very similar (including invocation and return values), but have different effects.

They are used for function throttling, and control functions are not frequently called, saving both client and server resources.

    • The Debounce () method focuses on the interval of function execution, where the call time of a function two times cannot be less than the specified time.
    • The throttle () method pays more attention to the execution frequency of the function, that is, the function is called only once within the specified frequency.

5.8 Template parsing

Underscore provides a lightweight template parsing function that helps us effectively organize page structure and logic.

I will introduce it through an example:

JS Code
  1. <!--to display the rendered label--
  2. <ul id="element" ></ul>
  3. <!--define templates to place template content in a script tag--
  4. <script type="text/template" id="TPL" >
  5. <% for (var i = 0; i < list.length; i++) {%>
  6. <% var item = list[i]%>
  7. <li>
  8. <span><%=item.firstName%> <%=item.lastName%></span>
  9. <span><%-item.city%></span>
  10. </li>
  11. <%}%>
  12. </script>
  13. <script type="Text/javascript" src="underscore/underscore-min.js" ></script>
  14. <script type="Text/javascript" >
  15. //Get render elements and template content
  16. var element = $ (' #element '),
  17. TPL = $ (' #tpl '). html ();
  18. //Create data that you may have obtained from the server
  19. var data = {
  20. List: [
  21. {firstName: ' <a href= ' # ' >Zhang</a> ', lastName: ' San ', City: ' Shanghai '},
  22. {firstName: ' Li ', lastName: ' Si ', City: ' <a href= ' # ' >Beijing</a> '},
  23. {firstName: ' Wang ', lastName: ' Wu ', City: ' Guangzhou '},
  24. {firstName: ' Zhao ', lastName: ' Liu ', City: ' Shenzhen '}
  25. ]
  26. }
  27. //Parse template, return parsed content
  28. var html = _.template (TPL, data);
  29. //Populate the parsed content with the rendered element
  30. element.html (HTML);
  31. </script>

In this example, we put the template content in a <script> tag, and you may have noticed that the type of the label is text/template rather than text/javascript because it cannot be run directly as a JavaScript script.

I also recommend that you put the template content in <script>, because if you write them in a <div> or other tag, they may be added to the DOM tree for parsing (even if you hide the tag).

_.template template functions can only parse 3 template labels (this is much simpler than smarty, JSTL):

<%%>: Used to contain JavaScript code that will be executed when the data is rendered.

<%=%>: For output data, it can be a variable, a property of an object, or a function call (the return value of the output function).

<%-%>: Used to output data while converting HTML characters contained in the data into solid form (for example, it converts double quotes to &quot;) to avoid XSS attacks.

<%-%> tags are often used when we want to display the HTML in the data as text.

Underscore also allows you to modify the form of these 3 tags, if we want to use {%}, {%=%}, {%-%} as tags, can be implemented by modifying the templatesettings, like this:

JS Code
    1. _.templatesettings = {
    2. Evaluate:/\{% ([\s\s]+?) \%\}/g,
    3. Interpolate:/\{%= ([\s\s]+?) \%\}/g,
    4. Escape:/\{%-([\s\s]+?)%\} /g
    5. }

In this example, we pass the template content and the data that needs to be populated to the template method, which is processed in the following order:

    • Parsing template content into executable JavaScript (parsing template tags)
    • Using the WITH statement to modify the parsed JavaScript scope to the data object we passed, which allows us to access the properties of the data object directly in the template through variable form
    • Perform parsed JavaScript (populate the template with data)
    • Returns the result after execution

We often encounter a situation where multiple calls to the template method render data to the same template.

Let's say we have a paging list where each piece of data is rendered through a template, and when the user goes to the next page, we get the next page of data and re-render it, and actually the template is the same each time it is rendered, but all the processing of the templates just described is always executed.

In fact, the underscore template method provides a more efficient way to call, we change the last two sentences in the above code to:

JS Code
    1. Parse the template and return the parsed content
    2. var render = _.template (TPL);
    3. var html = render (data);
    4. Populate the rendered element with parsed content
    5. element.html (HTML);

You will find subtle differences: When we call the template method, we pass only the content of the templates, and we do not pass the data, and the template method parses the contents of the templates, generates the parsed executable JavaScript code, and returns a function. The function body is the parsed JavaScript, so when we call the function to render the data, we omit the template parsing action.

You should store the returned function (as if I were storing it in a render variable), and then render the data by invoking the function, especially if the same template might be rendered more than once, which would improve the efficiency of execution (how much more, depending on the length and complexity of your template, But anyway, it's a good habit.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.