Knockout Study Notes (2)

Source: Internet
Author: User

This article is mainly used to record the testing and experience of learning working with observable arrays.

Observable is mainly used to modify and subscribe to a single individual. When we are dealing with a bunch of individuals and the UI needs to repeatedly display elements with the same style, the binding of these data depends on observable arrays.

Note that observable arrays focuses on the overall changes of elements in the array (including adding elements, deleting elements, changing element order, and so on ), instead of individual element changes (changes in some parts of the element ).

We can create an observable array in the JS file and initialize some of the elements:

1 var myObservableArray = ko.observableArray([2   { firstName: "Kazusa", lastName: "Touma" },3   { firstName: "Chiaki", lastName: "Izumi" },4   { firstName: "Yuki", lastName: "Nagato" }5 ]);

According to the original instructions:observableArrayIs actually an observable whose value is an array. That is to say, an observablearray is actually an observable, but the value of this observable is an array, not a string or number or other types. In the previous article, we can also observe that when calling or modifying the observable value, we need to use it as a function, that is, we need to add a bracket after identifier, this rule also applies to observablearray (after all, it is essentially an observable. In fact, I am wondering why knockout does not directly integrate the observablearray constructor into observable, it may be because all methods are different, or they are designed to be clearer in concept ). To obtain and modify the value of observablearray or its elements, we have created several P elements for display:

1 <p>The length of observableArray is: <span id="lengthOfArray"></span></p>2 <p>The second element of observableArray is: <span id="secondElement"></span></p>3 <p>The changed element: <span id="changedElement"></span></p>

In the JS file, we do the following:

1 $("#lengthOfArray").text(myObservableArray().length);2 $("#secondElement").text(myObservableArray()[1].firstName);3 myObservableArray()[2].lastName = "Charlie";4 $("#changedElement").text(myObservableArray()[2].lastName);

The last page is shown as follows:

In general, we can operate observablearray using the most basic array operation method similar to Javascript, but Ko's observablearray has more powerful features, which are summarized as follows:

  1. They can be used in all browsers (for example, the indexof method of JavaScript cannot be used in browsers earlier than IE8, while the indexof method of Ko can be used ).
  2. For methods to modify the array content, such as push or splice, Ko's method will automatically trigger the dependency tracing mechanism and make automatic changes to all subscribers and UIS.
  3. Ko's method is more concise in calling. For example, the push method only needs to be written as myobservablearray. Push (...) instead of myobservablearray (). Push (...).

I have some questions about Article 3: Which methods can omit brackets and which methods cannot? (At least length is not allowed, probably because length is counted as an attribute and not a method ?) Currently, the basic assumption is that the method can omit parentheses, but the attribute or element cannot.

This document will introduce some functions that can be used to read and write array information. To display my observablearray array more intuitively, I made the following changes to the JS file:

1 var i, length;2 for (i = 0, length = myObservableArray().length; i < length; i++) {3   $("<p></p>").appendTo($("p:last"));4   $("p:last").text("First Name: " + myObservableArray()[i].firstName + "; Last Name: " + myObservableArray()[i].lastName);5 }

The indexof method can return the index value of the first element in the array that is equal to the parameter you provide. If the array does not contain any element that meets the conditions,-1 is returned. The corresponding JS part is as follows:

1 $("#indexOfChiaki").text(myObservableArray.indexOf("Chiaki"));2 $("#indexOfCharlie").text(myObservableArray.indexOf("Charlie"));

The corresponding HTML section is as follows:

1 <p>The index of Chiaki is: <span id="indexOfChiaki"></span></p>2 <p>The index of Charlie is: <span id="indexOfCharlie"></span></p>

The effect is as follows:

The slice method is used to return the element value in the specified range in the array (if the second parameter is omitted, the element value is from the position of the first parameter to the end of the array by default). The JS part is as follows:

1 $("#testForSlice").text(myObservableArray.slice(2, 5));

The corresponding HTML section is as follows:

1 <p>Test for slice function: <span id="testForSlice"></span></p>

The effect is as follows:

Assume that the elements of our observablearray are in the initial state. Then, we will test methods such as pop, push, and shift. The original array style is appended to the left of each method.

Push is used to add the specified element at the end of the array. The JS part is as follows:

1 myObservableArray.push("Charlie");

The effect is as follows:

The pop method is used to delete and return the last element of the array. The JS part is as follows:

1 var test = myObservableArray.pop();2 alert(test);

The effect is as follows:

The unshift method is used to add a specified element to the array header. The JS part is as follows:

1 myObservableArray.unshift("Charlie");

The effect is as follows:

The shift method is used to delete and return elements starting with an array. The JS section is as follows:

1 var test = myObservableArray.shift();2 alert(test);

The effect is as follows:

The reverse method is used to invert the order of the array. The JS part is as follows:

1 myObservableArray.reverse();

The effect is as follows:

The sort method is used to sort arrays. The default sorting rules are sorted by letters. The JS part is as follows:

1 myObservableArray.sort();

The effect is as follows:

In addition, the sort method can also customize the sorting method. For example, you can customize a method to sort in reverse alphabetical order:

1 myObservableArray.sort(function(left, right) {2   return left === right ? 0 : (left < right ? 1 : -1);3 });

The effect is as follows:

I have a question about the sort custom sorting method. How does the left and right parameters provided to function implement sorting? How do the positive and negative values to be returned after comparison be applied to sorting? Maybe these answers can be found from the source code of knockout, which can be reserved for future research.

The splice method deletes and returns the specified number of elements starting from the specified position in the array. Its first parameter is the value of the specified index, and the second parameter is the number of elements to be deleted, the JS part is as follows:

1 var test = myObservableArray.splice(1, 3);2 alert(test);

The effect is as follows:

For more detailed methods available in array, MDN provides detailed documentation.

The following methods are new Ko methods not included in the default JavaScript method.

To test the effect of methods such as remove, I convert the array elements into the following form:

The remove method can delete elements that are equal to the specified values and return them as arrays. The JS part is as follows:

1 var test = myObservableArray.remove("Chiaki");2 alert(test);

The effect is as follows:

 

You can also customize the deletion conditions in remove. The JS section is as follows:

1 var test = myObservableArray.remove(function(item) {2   return item.length <= 5;3 });4 alert(test);

The effect is as follows:

 

The removeall method is used to delete an element equal to a specified Element in the array and return it as an array. The corresponding JS part is as follows:

1 var test = myObservableArray.removeAll(["Chiaki", "Kazusa", "Charlie"]);2 alert(test);

The effect is as follows:

If no parameter is added to the removeall method, the entire array is deleted and returned.

Since the destroy and destroyall methods are mainly related to Ruby and rails development, they can be reserved for future research.

Similarly, observablearray can also call the ratelimit attribute in the extend method to specify the latency, and then test the function when bindings is activated.

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.