Knockoutjs 3.X API Fourth Chapter Data Control flow foreach binding _javascript Tips

Source: Internet
Author: User

foreach Binding

A foreach binding is primarily used to loop through each element of the array property of the monitor, typically in the table label

Suppose you have a monitor attribute array, and whenever you add, delete, or reorder an array item, the binding will effectively update the UI's dom-insert or remove related items or reorder existing DOM elements without affecting any other DOM elements.

Of course, it can also be applied together with other control flows, such as if and with.

Example 1: Traversing the Monitor property array

This example applies to the foreach binding, which loops through the contents of the Monitor property array in a table label

<table>
<thead>
<tr><th>first name</th><th>last name</th></ tr>
</thead>
<tbody data-bind= "Foreach:people" >
<tr>
<td data-bind= " Text:firstname "></td>
<td data-bind=" Text:lastname "></td>
</tr>
</ tbody>
</table>
<script type= "Text/javascript" >
ko.applybindings ({
people: [
} FirstName: ' Bert ', lastName: ' Bertington '},
{firstName: ' Charles ', lastName: ' Charlesforth '},
{firstName: ' Denise ', LastName: ' Dentiste '}
]
};
</script>

Example 2: Adding or removing items

UI Source code:

 
 

View Model Source:

function Appviewmodel () {
var self = this;

Self.people = Ko.observablearray ([
{name: ' Bert '},
{name: ' Charles '},
{name: ' Denise '}
]); 
   
    self.addperson = function () {
Self.people.push ({name: "New at" + New Date ()});
Self.removeperson = function () {
self.people.remove (this);
}
}
Ko.applybindings (New Appviewmodel ());
   

Note 1: Use $data

As in the first two examples, a foreach followed by the name of the monitoring property array to loop, and foreach is followed by items that monitor the property array, such as FirstName and LastName.

When you want to reference the Monitoring property array itself, you can use this particular context $data, which he refers to is the Monitoring property array itself.

For example, the items in your monitoring attribute array do not have an explicit project name:

<ul data-bind= "Foreach:months" >
<li> the current
item is: <b data-bind= "text: $data" ></b >
</li>
</ul>
<script type= "Text/javascript" >
ko.applybindings ({
Months: [' before ', ' Feb ', ' Mar ', ' etc ']
};
</script>

If you want to, you can also use $data to reference items in the monitored array properties, such as:

<TD data-bind= "text: $data. FirstName" ></td>

In fact, this is superfluous. Because the default prefix for FirstName is $data, it can generally be omitted and not written.

NOTE 2: Use $index, $parent, and other contextual markers

You may find that in Example 2 the $index is used instead of the indexed value of the Monitoring property array (starting at 0), and of course $index is a monitoring property that automatically changes depending on the data, as shown in Example 2.

$parent represents a binding property outside the foreach bound loop, for example:

<H1 data-bind= "Text:blogposttitle" > 
 

Note 3: Use "as" to alias a foreach bound item

In note 1, you use $data.varibale to access items that monitor property arrays, but at some point you may need to give these items an individual name, that is, you can use as, for example:

<ul data-bind= "foreach: {data:people, as: ' Person '}" ></ul>

Now, as long as you use person in the Foreach loop, you can access the elements in the array.

There are also examples of nested use, which can be more complicated, such as:

<ul data-bind= "foreach: {data:categories, as: ' Category '}" >
<li>
<ul data-bind= "foreach: { Data:items, as: ' Item '} ' >
<li>
<span data-bind= ' Text:category.name ' ></span>:
<span data-bind= "Text:item" ></span>
</li>
</ul>
</li>
</ul>
<script>
var viewModel = {
Categories:ko.observableArray ([
{name: ' Fruit ', items: ['] Apple ', ' Orange ', ' Banana ']},
{name: ' vegetables ', items: [' celery ', ' Corn ', ' spinach ']}
]
};
Ko.applybindings (ViewModel);
</script>

Note 4: Do not use a foreach container and produce content

In some cases, you might want to copy the contents of the container label, for example, to generate the following DOM:

<ul>
<li class= "header" >header item</li>
<!--The following are generated From an array-->
<li>item a</li>
<li>item b</li> <li>item c</li
>
</ul>

In this case, we can't use a foreach binding in the UL tag, and the way to solve this problem is to use a foreach binding without a container:

<ul>
<li class= "header" >header item</li>
<!--ko foreach:myitems-->
<li> Item <span data-bind= "text: $data" ></span></li>
<!--/ko-->
</ul>
< Script type= "Text/javascript" >
ko.applybindings ({
myitems: [' A ', ' B ', ' C ']
});
</script>

This uses the virtual element container,<!--ko--> and <!--/ko-->. Just like the virtual bindings mentioned in the previous section.

Note 5: Detect and handle array changes

When you modify the contents of the model array (by adding, moving, or deleting its items), a valid difference algorithm is used in the foreach binding to calculate what happens when something changes.

When you add an array item, foreach makes a new copy of your template and inserts it into the existing DOM
When you delete an array item, foreach deletes the corresponding DOM element directly
When you reorder an array item (keeping the same object instance), foreach usually simply blends the corresponding DOM element into its new location

Remark 6: Destroy the project

Sometimes you might want to do a delete tag for a data item, but you don't actually delete the item. This approach is known as non-destructive deletion.

By default, the foreach binding will be skipped (that is, hidden) marked to remove any array items. If you want to display these items, use the includedestroyed option. For example

<div data-bind= ' foreach: {data:myarray, includedestroyed:true} ' > ...
</div>

Note 7: Use animation transitions to improve the user experience

If you need to run some custom logic on the generated DOM element, you can use Afterrender/afteradd/beforeremove/beforemove/aftermove these callback functions.

Here is a simple example of using Afteradd, applying the classic "Yellow fade" effect to add items. It takes the jquery plugin color to make the background color animated.


The source code is as follows:

<ul data-bind= "foreach: {data:myitems, Afteradd:yellowfadein}" >
<li data-bind= "text: $data" ></li >
</ul>
<button data-bind= "Click:additem" >Add</button>
<script type= "text/ JavaScript ">
ko.applybindings ({
myItems:ko.observableArray ([' A ', ' B ', ' C ']),
Yellowfadein: function (element, index, data) {
$ (Element). Filter ("Li")
. Animate ({backgroundcolor: ' yellow '}, MB)
. Animate ({backgroundcolor: ' White '},);
},
additem:function () {this.myItems.push (' New item ');}
);
</script>

Some specific details.

Afterrender-The callback function that is executed the first time foreach initializes. KO provides the following parameter callbacks:

An array of inserted DOM elements

Data items

Afteradd-the callback function after foreach adds a new project. KO provides the following parameter callbacks:

DOM node
Index of the added array element
The added array element

Beforeremove-the callback function when an array item has been deleted. Here the most obvious use of jquery's $ (domnode). fadeout () animation removes the corresponding DOM node. KO provides the following parameter callbacks:

Delete a DOM node

Index of the element of the array being deleted

Deleted array elements

Beforemove-a callback function where an array item has changed position in an array, but the corresponding DOM node has been moved before. Note that the beforemove applies to all of the array elements, so if you insert a new item at the beginning of an array, then the callback (if specified) triggers all the other elements because their index position is incremented. You can use Beforemove to store the original screen coordinates of the affected element so that you can recall the animation action in Aftermove. KO provides the following parameter callbacks:

May be a moved DOM node

The index of the moved array element

Moved array elements

Aftermove-the callback function where the array entry has changed position in the array, KO provides the following parameter callbacks:

DOM nodes that may have been moved

The index of the moved array element

Moved array elements

The above is a small set to introduce the Knockoutjs 3.X API Fourth chapter of the data Control flow foreach binding, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.