5 KO instances take you for a B to fly with you

Source: Internet
Author: User

Knockoutjs hereinafter referred to as KO, is a JavaScript MVVM framework.

In the MVC 4 project template, Knockoutjs is referenced by default, and I have no formal contact with it for a period of 4 months.

Before using it, to do a master-slave relationship maintenance, probably to write a bunch of clonenode/append, JS level general classmate, to write such a business page, probably to write hundreds of thousands of line JS just line.

This example is not about the use of Ko, but rather a slightly more complex business that I have worked on in the project as a prototype, and a deep understanding of how to use KO to take you to the B to fly with you. So, if you don't know Ko, you can start by looking at Ko's documentation:

Http://knockoutjs.com/documentation/introduction.html

Example (VS2013 MVC5):

http://files.cnblogs.com/xling/KOExamples.7z

Four-level linkage

A penny stumped hero Han, once, there is a brother, there is a 5-level linkage business task, involving 9 tables, on the same page. In short, the faint sky, also did not finally finish.

In this example: foreach/click/bind/attr/$parent/$parentContext/visible/$data/$root/textinput/$index

Bind

In the Click Binding Description document in the second section, note 2:accessing the event object, or passing more parameters.

If the event binding does not specify a parameter, the default parameter is the model data that is currently bound to the HTML object.

$parent/$parentContext

$parent refers to the parent model data of the currently bound model data.

$parentContext refers to the context of the parent model data for the currently bound model data.

Visible

The classic scene of master-slave relationship is: Click the master record, display the corresponding from the data list.

In HTML, the simplest way to achieve this is to show and hide, or generate dynamically.

If the data is submitted based on AJAX, dynamic generation does not matter, the final data are recorded in the JS object. However, if it is based on form form submission, the dynamic generation of sub-lists is not, so this example uses show/hide.

Several points on the sample interface

In VS, pressing F5 debug, after opening IE , you can see a Function Code entry in the solution that you can debug:

Serial Number

The sequence number uses the $index, $Index exists only in foreach, and is a child of the $context.

Total

That is, the length of the array

Because companys is defined as follows:

this. Companys = Ko.observablearray ();

Ko.observablearray () returns a Function object that also has a length property, but its value is always 0

Companys () returns the _lastvalue array , so, at the time of binding, it is written:

Text:companys (). length, not text:Companys.length

It depends on your companys definition. If This.companys = [...] then the binding will be written text:Compansys.length.

currently active object

After clicking on a line, the list is displayed, which is done by modifying the iscurrent in the model data.

<data-bind= "Click:SetCurrent.bind (null, $data, $root), Attr:{class:iscurrent ()? ' Success ': '}'>
3 varBaseobj =function () {5 ///<summary> can set the base class for the currently active object </summary>9     //whether the current object One      This. Iscurrent = Ko.observable (false); -      This. Setcurrent =setcurrent; the }; -  + varSetcurrent =function(o, oc) { + ///<summary> Set the current active object </summary> at ///<param name= "O" type= "Object" > Objects to be set as active </param> - ///<param name= "OC" type= "Object" > Active object's recorder </param> -  -     if(O = =NULL) in        return; -  -     //Turns the original active object into an inactive object. *     if(OC. Current! =NULL)Panax NotoginsengOc. Current.iscurrent (false); -  AOc. Current =o; +Oc. Current.iscurrent (true); $}

The visible of the child list is also bound to the iscurrent:

<!---<data-bind= "Foreach:products, visible:i Scurrent () ">   companys's scope of action ... the scope of  products ...

Thus, when the iscurrent of the master record changes, the sub-list is displayed/hidden as it changes.

Drag sort

The use of the drag plugin in this example is the sortable provided by the jquery UI

At first I was fetching the port code in the drag-adjusted cell (TD) to reorganize the model data.

However, the same port code is allowed to appear two times in this list. So there's a problem.

It doesn't have to be that complicated, actually.

Ko has a datafor API that can be used directly.

1 varSortregportsbyuiseq =function () {3     varPorts = [];5$ ("tbody tr"). each (function(i, tr) {7         //get bound to a data object on a row9         varPort =ko.datafor (TR); One         Ports.push (port); -     }); -     VMs. Regports (ports); +}

Conditions

The conditions of the business are as follows:

If it is a price, only one piece of data is allowed. can have no data.

Automatically brings the "less than" of the previous bar to the next "greater than". Because "greater than" cannot be entered manually.

Controls whether the new button is displayed or not with the following syntax:

Visible: (fak_teu_formula_mode () = = 1 && $data. FAK (). length < 1| | (Fak_teu_formula_mode ()! = 1)

Fak_teu_formula_mode () = = 1 is a price

$data. FAK (). length < 1 i.e. no data currently

Automatically bring the value of the previous bar to the next implementation:

 // range_to the value before the change  this . _rangeto = 0;  //  this . Range_to.subscribe (Dofunction (VM. rangetochanged, this   this . Range_to.subscribe (function   (o) { // /<summary>change, Save the Range_to value for later comparison </summary>  Self._rangeto = self. Range_to.peek () | | 0; // .peek () returns the last value of the observable object }, null , " BeforeChange ") 

A range_to and a _range_to are defined here. The _range_to is used to save the old values.

Also defined are two subscriptions for range_to, one no event, one specified event BeforeChange

The Subscription (subscribe) method is executed when the observable object has changed.

BeforeChange, that is, before changing the value.

Specific how to pass values to the next record, as defined in the Rangetochanged method.

Calculation results

The data items that participate in the calculation must be observable. No other special instructions.

MVC Action parameter

A large number of form items, displayed on the page, not casually entered, can be submitted, which requires a validation rule.

MVC combined with Jquery.validate to the client's validation is perfect, basically do not write a sentence JS code can handle most of the data validation. This is because when MVC outputs HTML form items, the dataannoation of the model is converted to data-val-xxx.

What if you want to use KO and don't want to lose the functionality that MVC offers?

Custom Helper

@helper A (string prop) {   @Html. TextBox (prop, NULL, new {Data_bind = string. Format ("Value:{0},attr:{{name: ' routes[' + $parentContext. $index () + ']. ports[' + $index () + ']. {0} '}} ", prop), @class =" Form-control Input-sm "})} @helper B (string prop) {
@Html. Hidden (prop, NULL, new {Data_bind = string. Format ("Value: $index, Attr:{{name: ' routes[' + $parentContext. $index () + ']. ports[' + $index () + ']. {0} '}} ", prop)})
} @helper C (string prop) {
@Html. CheckBox (prop, False, new {Data_bind = string. Format ("Checked:{0},attr:{{name: ' routes[' + $parentContext. $index () + ']. ports[' + $index () + ']. {0} '}} ", prop)})
}

Use

< TD >@A (Helper.getpropertyname (Html, M = m.portcode))</td><  td>@c (Helper.getpropertyname (Html, M = m.isback))</TD  >

This makes the KO and MVC seamless together.

5 KO instances take you for a B to fly with you

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.