Using the observable array (working with observable arrays)

Source: Internet
Author: User
Tags javascript array ruby on rails

observable Array (observable arrays)

If you want to detect and respond to changes in an object, you should use observables. If you need to probe and respond to changes in a collection object, you should use Observablearray. It is useful in many scenarios, such as a collection of list data that you want to display/edit on the UI, and then add and delete the collection.

Example:

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

To learn how to bind to the UI and if you modify the value of the data, see the Simple list example.

key point: The monitoring array tracks the objects in the array, not the state of the objects themselves.

Simply placing an object in the Observablearray does not make the property changes of the object itself to be monitored. Of course you can declare that the object's properties are observable. A Observablearray only monitors the objects he owns and notifies them when they are added or deleted.

pre-load a monitoring array Observablearray

If you want your monitoring array to have some initial values at the beginning, you can add these initial objects to the constructor at the time of declaration. For example:

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

In fact, a observablearray is actually a observable monitoring object, but his value is an array (Observablearray also added a lot of other features, described later). So you can get the original array object of JavaScript just like the value of normal observable, you can get the value of yourself simply by calling the parameterless function. For example, you can get its value as follows:

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

Theoretically you can manipulate these arrays using any native JavaScript array function, but KO provides better function equivalence functions, which are useful because:

    1. Compatible with all browsers. (for example, indexof cannot be used on IE8 and earlier versions, but Ko's own indexof can be used on all browsers)
    2. In terms of array manipulation functions (such as push and splice), KO's own way can automatically trigger dependency tracking and notify all subscribers of its changes, and then let the UI interface automatically update accordingly.
    3. Syntax is more convenient, call Ko's push method, only need to write this: Myobservablearray.push (...). For example, the native array of Myobservablearray (). Push (...) It's much more useful.

The following is an explanation of Observablearray's read and write related functions.

IndexOf

The INDEXOF function returns the first index equal to the item of your parameter array. For example: Myobservablearray.indexof (' blah ') returns the index of the first array item equal to blah at 0 for the first index. If no equality is found, it returns-1.

Slice

The slice function is an equivalent function of observablearray relative to the JavaScript native function slice (returns a collection of all objects from a given start index to the end index). Call Myobservablearray.slice (...) Equivalent to invoking a JavaScript native function (for example: Myobservablearray (). Slice (...) )。

Operation Observablearray

Observablearray provides a series of familiar functions that can be used to modify the contents of the data and inform listeners.

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

All of these functions are equivalent to the JavaScript array native function, and the only different array changes can inform the Subscribers:

    • Myobservablearray.push (' Some new value ') adds a new item at the end of the array
    • Myobservablearray.pop () deletes the last item of the array and returns the item
    • Myobservablearray.unshift (' Some new value ') adds an item to the head of the array
    • Myobservablearray.shift () deletes the first item in the array header and returns the item
    • Myobservablearray.reverse () Flips the order of the entire array
    • Myobservablearray.sort () to sort the array

By default, it is sorted by character (if it is a character) or numerically (in the case of a number).

You can sort through a sort function that takes 2 parameters (representing the items that need to be compared in the array), returns 1 if the first item is less than the second item, or 1, or returns 0. For example: Use LastName to sort the person, you can write this: Myobservablearray.sort (function (left, right) {return left.lastname = = right.lastname? 0 : (Left.lastname < Right.lastname -1:1)})

    • Myobservablearray.splice () Deletes the specified start index and the specified number of array object elements. For example, Myobservablearray.splice (1, 3) deletes 3 elements (2nd, 3, 4 elements) starting at index 1 and returns these elements as an array object.

For more information on the Observablearray function, refer to the equivalent JavaScript array standard function.

Remove and RemoveAll

Observablearray adds some functions that are not yet useful by default in JavaScript arrays:

    • Myobservablearray.remove (Someitem) deletes all elements that are equal to Someitem and returns the deleted elements as an array
    • Myobservablearray.remove (function (item) {return Item.age < 18}) removes all elements of the age attribute less than 18 and returns the deleted element as an array
    • Myobservablearray.removeall ([' Chad ', undefined]) removes all elements equal to ' Chad ', 123, or undefined and will be deleted as an array of elements returned
    • Myobservablearray.removeall () Removes all values and returns as a new array.

Destroy and Destroyall (note: Usually only related to Ruby on Rails developers) (Useless, copy the http://www.cnblogs.com/TomXu/archive/2011/11/22/2256820.html of others completely)

The Destroy and Destroyall functions are developed for use by Ruby on Rails developers:

Myobservablearray.destroy (Someitem) finds all elements equal to Someitem and adds a property _destroy to them, and assigns a value of true

Myobservablearray.destroy (function (someitem) {return Someitem.age < 18}) find all elements with an age attribute of less than 18 and add an attribute _destroy to them, and assigns a value of true

Myobservablearray.destroyall ([' Chad ', undefined]) find all the elements equal to ' Chad ', 123, or undefined and add an attribute _destroy to them, and assign a value of True

So, what is _destroy for? As I mentioned, it's just for rails developers. In the rails development process, if you pass in a JSON object, the Rails framework is automatically converted to a ActiveRecord object and saved to the database. The Rails framework knows which objects are present in the database and what needs to be added or updated, and the tag _destroy is true to tell the framework to delete the record.

Note: When Ko render a foreach template, an element with the _destroy attribute and a value of true are automatically hidden. So if your "delete" button calls the Destroy (Someitem) method, the corresponding elements on the UI interface will be automatically hidden, and then when you commit the JSON object to rails, This element item will be deleted from the database (while other element items will be inserted or updated normally).

delay and/or suppress notification of changes in monitoring properties (delaying and/or suppressing change notifications)

In general, when a value changes, the notification of the monitoring attribute is triggered immediately. However, in some cases (such as the change is repetitive, or the cost of dealing with a change in value is larger), it is necessary to postpone or limit notification generation. You can use the ratelimit extension at this time, for example:

// ensure it notifies about changes no more than once per 50-millisecondperiod MyViewModel.myObservableArray.extend ({ratelimit:50});

Using the observable array (working with observable arrays)

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.