Beginner Knockoutjs Record 2--observables monitoring properties (2 Observable Arrays monitoring Array)

Source: Internet
Author: User
Tags button type javascript array

1 Observable Arrays Monitoring array

If you want to monitor and respond to changes in an object, you should use observable to monitor the properties, and if you want to monitor and respond to changes in a collection of objects, then use Observablearray to monitor the array, which is useful in many scenarios, such as when you want to render or edit multiple values, When you need to work with multiple repeating fragments on the UI like a list item is added or removed.

For example

var myobservablearry = Ko.observablearray ();  // initally an empty arraymyobservablearray.push (' Some value ');            // Adds The value and notifies observers

Here's an example of how you can bind the monitor array to the UI and let the user use it to see a simple list below, in this example, how to bind an array

Note that the "ADD" button is only available if you already have input, view the HTML source code to learn how to use the "enable" binding

View's Code

<form data-bind= "Submit:additem" >    New item:    <input data-bind= ' Value:itemtoadd, Valueupdate: "Afterkeydown" '/>    <button type= "Submit" data-bind= "Enable:itemtoadd (). length > 0" >add </button>    <p>your items:</p>    <select multiple= "multiple" width= "data-bind=" Options:items "> </select></form>

The code of the View Model

varSimplelistmodel =function(items) { This. Items =Ko.observablearray (items);  This. Itemtoadd = Ko.observable ("");  This. AddItem =function() {        if( This. Itemtoadd ()! = "") {             This. Items.push ( This. Itemtoadd ());//Adds the item. Writing to the ' items ' Observablearray causes any associated UI to update.             This. Itemtoadd ("");//Clears the text box, because it ' s bound to the ' itemtoadd ' observable}}.bind ( This);//ensure that ' this ' is always the This view model}; Ko.applybindings (NewSimplelistmodel (["Alpha", "Beta", "Gamma"]));

Key Point: Monitoring array Tracking monitors the objects in the array, not the state of those objects

Simply putting an object into the monitoring array does not result in the object's own properties being monitored. Of course, if you want to be able to monitor these properties, it's another monitoring. A monitoring array simply tracks the objects it holds and notifies listeners when those objects are added or removed.

Prepopulating and Observablearray preloaded with a monitoring array

If you do not want your monitoring array to be empty at first, but to contain initial initial objects, you need to pass these objects as a data into its constructor, for example

// This observable array initially contains three objects var anotherobservablearray = Ko.observablearray ([    "bungle", type: "Bear" },    " George ", type:" Hippo " },    " Zippy ", type:" Unknown " }]);

Reading information from an observablearray reading the data of the monitoring array

Behind the scenes, a monitoring array is actually a monitoring property, and the value of this monitoring property is an array (additional useful features added to the monitoring array). Therefore, you can call the parameterless function of the monitoring array to get its underlying array value, just like any other monitoring property, and then you can read the data from this array, for example

Alert (' The length of the array is ' + myobservablearray (). Length), alert (' The first element is ' + Myobservablea Rray () [0]);

Technically, you can use any of the original JavaScript array functions to manipulate its underlying array, but it's usually better to look at the options behind it, and Ko's monitoring array has its own more useful equivalent function because:

1. They can be used on all browsers with good compatibility (for example, IE8 and earlier versions of JavaScript that do not support OST indexOf functions, but Ko's indexOf can be used anywhere)

2. In the function of manipulating arrays, such as push and splice, the KO method's automatic trigger dependency tracking mechanism allows all subscribers to be notified when data changes, and automatically updates UI elements

3. Its syntax is more convenient, such as the call Ko's push method, only need to write Myobservablearry.push (...), which is more than calling the underlying array of the push notation Myobservablearray (). Push (...) A little bit better.

Here are some ways to manipulate the array of controls

IndexOf

The IndexOf function returns the index of the first array item that is equal to your argument. For example, Myobservablearray.indexof (' blah ') returns a 0-based index of the first array item equal to ' blah ', and returns 1 if no equal array entry is found.

Slice

The slice function of the monitoring data is equivalent to the JavaScript OST slice function (which also means that it returns an array item for the given start and end index), and calls the Myobservablearray.slice (...). Equivalent to calling the underlying array with the same name Method Myobservablearray (). Slice (...)

Manipulating an Observablearray operation monitoring array

The monitoring array provides a familiar set of functions to manipulate the contents of the array, and notifies the listener

Pop, push, shift, unshift, reverse, sort, splice

All of these functions are equivalent to running their JavaScript native functions and can notify listeners of the occurrence of the change:

Myobservablearray.push (' Some new value ') adds a new item to the array

Myobservablearray.pop () Moves the last item of the divisor group and returns it

Myobservablearray.unshift (' Some new value ') Inserts a new item at the beginning of the array

Myobservablearray.shift () Moves the first item of the divisor group and returns it

Myobservablearray.reverse () Reverses the order of the entire array

Myobservablearray.sort () sorting an array

The default sort order is character sort (character type) or numeric sort (numeric type), you can also pass in a custom sorting function, you need to receive two parameters (two objects in the array) and when the first value hour returns a negative number, the first value is large when a positive number is returned, equal to return 0. For example, sort the data in the last name to a ' person ' object as follows

Myobservablearray.sort (function(left, right) {   return Left.lastname = = Right.lastname? 0: (Left.lastname < Right.lastname -1:1)})

Myobservablearry.splice () Removes the specified number of array elements from the specified starting index and returns the removed element as an array. For example, Myobservablearray.splice (1,3) removes 3 elements (that is, the 2,3,4 element) starting at index 1 and returns them as an array

For more details on monitoring array functions, please refer to the equivalent official website document standard JavaScript array functions

Remove and RemoveAll

    

  

Beginner Knockoutjs Record 2--observables monitoring properties (2 Observable Arrays monitoring Array)

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.