KnockOut bound foreach binding (mvc+knockout)

Source: Internet
Author: User

When to use the foreach binding

The foreach binding copies a section markup language, which is HTML, for each element in the array, and binds the section Markup language and every element inside the group. This is useful when we present a set of list data, or a table.

If you bind an array that is a "monitor array", observable array, (as in WPF observablecollection<t>). When you add or remove, or reorder elements inside an array, the UI interface is updated dynamically. And it does not affect the original DOM element at this time. This is much more efficient than rebuilding an array directly from us and binding elements.

Of course, foreach also supports nested bindings, or other workflow bindings such as if or with.

Example 1: Iteration binds an array

Generates a read-only table of one row of data for each element in an array.

@{Layout=NULL;}<script src= "~/scripts/jquery-1.10.2.js" ></script><script src= "~/scripts/knockout-3.2.0.js" > </script><table> <thead> <tr><th>first name</th><th>last NAME&LT;/TH&G t;</tr> </thead> <tbody data-bind= "Foreach:people" > <tr> <td data-bind = "Text:firstname" ></td> <td data-bind= "Text:lastname" ></td> </tr> </t Body></table><script type= "Text/javascript" >ko.applybindings ({people: [{firstName:' Bert ', lastName: ' Bertington '}, {firstName:' Charles ', lastName: ' Charlesforth '}, {firstName:' Denise ', lastName: ' Dentiste ' }        ]    });</script>

The effect is as follows:

First Last
namename
Bert Bertington
Charles Charlesforth
Denise Dentiste

Example 2: Add an addition and removal method to the system table in Example 1

The following example shows that if you bind an array that is a monitoring array, then the UI interface will be synchronized with the changes to the group.

People
    • Name at position 0: Bert Remove
    • Name at position 1: Charles Remove
    • Name at position 2: Denise Remove

Add

@{Layout=NULL;}<script src= "~/scripts/jquery-1.10.2.js" ></script><script src= "~/scripts/knockout-3.2.0.js" > </script>Name at position<span data-bind= "text: $index" > </span>: <span data-bind= "Text:name" > </span> <a href= "#" data-bind= "click: $parent. Removeperson" >Remove</a> </li></ul><button data-bind= " Click:addperson ">add</button><script type=" Text/javascript ">functionAppviewmodel () {varSelf = This; Self.people=Ko.observablearray ([{name:' Bert '}, {name:' Charles '}, {name:' Denise ' }        ]); Self.addperson=function() {Self.people.push ({name:"New at" +NewDate ()});        }; Self.removeperson=function() {Self.people.remove ( This); }} ko.applybindings (NewAppviewmodel ());</script>
Parameters
      • Main parameters

      • Pass the array that you want to iterate over to foreach. For each array element, the foreach binding outputs a Hypertext Markup language.

      • You can also give a foreach binding a JavaScript literal that contains the data property that you want to iterate over, and this literal can have other properties, for example afterAdd , or you includeDestroyed can see the next example.

      • If you are bound to a monitoring array, adding or removing a foreach binding on the contents of the array will add or remove the DOM element from the UI interface.

      • Other parameters

        • No
Point 1: Use $data to point to each piece of data in the array

As shown in the example above. A foreach binding can point to an array of properties for each piece of data. For example, FirstName and LastName in Example 1. However, if we want to point to the array itself, what should we do, at this point we can use the $.data. In a foreach binding, $data refers to the current element item of the array.

@{    null;} <script src= "~/scripts/jquery-1.10.2.js" ></script><script src= "~/scripts/knockout-3.2.0.js" > </script><ul data-bind= "Foreach:months" >    <li>        <b data-bind= "text: $data" ></b>    </li></ul><script type= "Text/javascript" >    ko.applybindings ({        Months: [' Jan ', ' Feb ', ' Mar ', ' etc ']    }); </script>

The effect is as follows

    • The current item is: Jan
    • The current item is: Feb
    • The current item is: Mar
    • The current item is: etc

Of course, if you have to do this, you can add one to each attribute you point to $data前缀 . For example, you can also write in Example 1 as follows, although this is not necessary because the default context is $data :

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

Point 2: Use $index, $parent, and other contextual properties

As we saw in Example 2. You can use $index to represent the zero-based index of the current item in the array.$index是一个监控属性,当数组的项变更的时候$index也会自动更新。

Similarly, you can also use$parent来指向foreach外的数据。如果foreach对应的是viewmodel的直接子元素,那么$parent就是指的viewmodel

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

More about$index和$parent的资料可以去看 binding context properties.

Point 3: Assign an alias to a foreach item with AS

I want to describe it in point 1. We can refer to each array item with $data context variables. However, in some special cases, it is more convenient to use an alias for the current item. Especially in multi-layered nesting structures:

The syntax for using aliases is as follows:

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

Now, anywhere in the Foreach loop, the binding can point to the current people array item based on person. This syntax is useful in multi-layered foreach nested scenarios. For example:

<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 ([            ' Fruit ', items: [' Apple ', ' Orange ', ' Banana ' ]},            ' vegetables ', items: [' celery ', ' Corn ', ' Spinach ' ]}        ]    };    Ko.applybindings (ViewModel); </script>

Note: Remember to assign a value to an alias through as, passing a string ‘category‘ , not as: category ), because we are going to give the variable an alias instead of passing an identifier variable past.

Note 4: Use foreach when there is no container element

In some cases, you want to bind a markup language HTML through foreach, but there is no element for the foreach binding. For example, the following scenario:

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

In this case, no element is available for the foreach binding. You can't put it inside the UL because it will also put the header in the copy loop. You can not put other elements in the UL inside, because UL inside only allowed to put<li>元素。

To deal with this situation. We can use no container binding syntax. The case is dependent on the HTML annotation tag. As follows:

<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 ({        ' A ', ' B ', ' C '    )}); </script>

<!-- ko -->and <!-- /ko --> annotations as the beginning and end of the label, define a dummy element to contain the markup language we need to re-reference inside, knockout understand this virtual element syntax. We can actually have an HTML element to use it.

Point 5: How array changes are detected and processed

When you modify the value of a bound cooked, for example by adding a delete move, the foreach binding detects which item has been changed by using a valid distinguishing syntax. So, being able to change the DOM elements of the predicted match, it's assumed that knockout can handle arbitrary and simultaneous changes.

    • When I add an array item, foreach we will draw a new DOM element based on our template to insert into the original DOM element.
    • When we delete an item, the foreach associated DOM element is removed.
    • When we move related array items, foreach only the relevant DOM elements will be moved.

Note that rearranging the permutations is not certain: you need to make sure that our elements want to operate fast enough. , it is optimized to detect only a small number of array item changes. When there are many elements that change at the same time, knockout chooses to perform the deletion and then re-add it instead of just moving the DOM element.

Point 6: Delete items are hidden by default

Sometimes you want to mark an array item as deleted, but it's not really deleted. This is what we call the "non-destructive deletion". For more information you can see the Destroy function on observableArray .

The default foreach binding will simply hide the item being deleted. If you want to see items that are not really deleted, you can use them includeDestroyed参数 . For example

<div data-bind= ' foreach: {data:myarray, includedestroyed:true} ' >     ... </div>
Important 7:dom element post-processing or generating animations

If we want to add more custom logic when building DOM elements we can use, afterRender //// afterAdd beforeRemove beforeMove afterMove These callback functions

Note: These callback functions are animated in order to generate a list change. For some complex requirements, we can customize the binding with custom bindings.

@{Layout=NULL;}<script src= "~/scripts/jquery-1.10.2.js" ></script><script src= "~/scripts/jquery.color-2.1.2.js" ></script><script src= "~/scripts/knockout-3.2.0.js" ></script><ul data-bind= "foreach: { Data:myitems, Afteradd:yellowfadein} "> <li data-bind=" text: $data "></li></ul><button data-b Ind= "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 '}, 200). Animate ({backgroundcolor:' White '}, 800); }, AddItem:function() { This. Myitems.push (' New item '); }    });</script>

The effect is as follows

More details:

  • afterRender-Called when the foreach template element is inserted into the document. This callback function is called at the first initialization and each subsequent addition. The following arguments are passed to the callback function:

    1. An array of inserted DOM elements
    2. The data element that is bound to itself
  • afterAdd-and afterRender很像 , however, it is called when the element is added, and is not invoked the first time it is initialized. Commonly used to perform element fading $(domNode).fadeIn() This function receives the following parameters:

    1. Increases the DOM node.
    2. Increase the index of an element
    3. Added array elements
  • beforeRemove-Called when an array element is removed, but the associated DOM element is not removed. A is beforeRemove commonly used to perform the fade out of a DOM node. $(domNode).fadeOut() In this case knockout does not know how long you want to set the fade time, so for the element removal, to be removed in the callback function manually. The function receives the following parameters:

    1. Array nodes that should be removed
    2. Index of the group element being shifted
    3. The removed array element
  • beforeMove-executes when an array element changes position, but the associated DOM element has not been moved. Note Beforemove  将会对所有索引改变的数组元素有效。 So, if you insert an item at the beginning of an array element, then the aftermove callback function is valid for all elements. Because the index of all the elements is changed by 1. We can use it. beforeMoveto record the value of the pre-move element and then use it in Aftermove. The callback function receives the following parameters:

    1. The DOM node that you intend to move
    2. Index of the moved array element
    3. Moving an array element
  • afterMove-called after the position of the array element has been changed, and is called after foreach has updated the DOM element afterMove 将会对所有索引改变的数组元素有效。 so if you insert an item at the beginning of the array element, then the Aftermove callback function will be valid for all elements. Because the index of all the elements is changed by 1. The callback function receives the following parameters:

    1. A DOM node that has already been removed
    2. Move the index of an array element
    3. The removed array element

更多的例子afterAddand beforeRemove please see animated transitions.

Knockout Paging demo:http://www.cnblogs.com/santian/p/4342777.html

Knockout official website: http://knockoutjs.com/documentation/foreach-binding.html

This address: http://www.cnblogs.com/santian/p/4379445.html

Blog address: Two days a day, three days

Reprint please indicate the original source of the article in the form of hyperlink.

KnockOut bound foreach binding (mvc+knockout)

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.