In the previous Knockoutjs Learning series (i) Ko first experience article mentioned, ko data-bind = "xx:oo" binding Dafa in addition to binding text, value and other content, can also bind visible, style and other appearance attributes, can also bind click, TextInput and other events, and even control procedures. A variety of fancy bundles that absolutely satisfy your fantasies.
The following is a brief talk about the use of various bindings, mainly according to the binding attributes into the performance class, Process class and interaction class three kinds.
Performance class Properties
Performance class binding attributes are visible, text, HTML, CSS, style, attr several, in addition to CSS to represent the class of CSS, the others are well understood. Of course, style inside the name to be consistent with JS, to remove-to the hump named, the following model:
<!--HTML code--> <div data-bind= "Visible:shouldshowmessage" >you'll-you-when "shouldshowm Essage "holds a true value.</div> <div>today ' s message is: <span data-bind= ' Text:mymessage ' ></span ></div> <div data-bind= "html:details" ></div> <div data-bind= "CSS: {profitwarning: Currentprofit () < 0} ">css class binding test</div> <div data-bind=" style: {color:currentprofit () < 0 ? ' Red ': ' Black '} ' >css style binding test</div> <a data-bind= ' attr: {href:url, title:urltitle} ' >report& lt;/a>//JS code var ViewModel = {ShouldShowMessage:ko.observable (true),//message initially visible Mymessage:ko Observable (),//initially blank details:ko.observable (),//initially blank (currentProfit:ko.observable),//Po Sitive value, so initially we don ' t apply the "Profitwarning" Class currentProfit:ko.observable (150000),//Positive Valu E, so initially black URL:KO.OBSERVABLe ("year-end.html"), Urltitle:ko.observable ("including final year-end Statistics")}; Ko.applybindings (ViewModel); Apply Binds
The effect is this:
The previous article also said that in addition to passing a single attribute in the Xxoo, you can also pass the JSON object, which means that you can combine binding attributes, such as:
<!--HTML code-->
<div data-bind= "{visible:shouldshowmessage, Text:mymessage, CSS: {profitwarning: Currentprofit () < 0}} "> You'll be
shouldshowmessage" holds a true value.
The effect of course is this:
The setting of the performance class is relatively simple, it should be noted that many of the properties of the performance class do not need dynamic change, this time can be used in ViewModel set to implement the centralized initialization of data, but do not set them to be observers, such as:
JS code
var viewModel = {
shouldShowMessage:ko.observable (true),//message initially visible
mymessage: ' This text does not need to be dynamically updated '//initially blank
Process Class Properties
Process classes include foreach, if, Ifnot, with, and more advanced "component" bindings, if and ifnot are similar to visible, except that if the corresponding component is removed directly from the DOM, visible simply controls the hidden display. Component is still inside the DOM. With and JS with the same effect, is the extension of the scope chain, in simple terms is in front of the variable added a ' prefix. ' Here is a brief introduction to Foreach,component and template binding.
Look at the code:
<!--HTML code--> <p> test foreach binding </p> <ul data-bind= "Foreach:people" > <li> no.<span data-bind= "text: $index" > </span> people ' s name: <span data-bind= "Text:name" > </span> <a href= " # "data-bind=" click: $parent. Removepeople ">RemovePeople</a> <a href=" # "data-bind=" Click:remove "> remove</a> </li> </ul> <input type= "button" data-bind= "Click:addpeople" value= "Add"/> var list Model = function () {//Set the value of the People array (people is actually an array of functions), using foreach to traverse the array object//ul,li corresponding to the people and people subkeys, so when binding inside Li, The scope is the People subkey {name ...} , in order to invoke the people external removepeople need to use $parent///If this is {name ...} in the remove,remove inside the call.
Corresponds to the current Li item, and the scope is the current field without $parent. This.people = Ko.observablearray ([{name: "Mark zake", Remove:function () {that.people.remove (this);//Note the current object (that is, {name ...). and scopes, without having to manage HTML tags, pure JS is simple to understand}}, {name: "James Lebo", Remove:function () {that.people.remove (this);}, {name: "Green Deny ", Remove:function () {That.people.remove (this);
}}
]);
Addpeople internal calls to the method of the sibling people, this will change and should be saved in advance this is passed in.
var that = this; This.addpeople = function () {That.people.push ({name:new Date (). todatestring (), remove:function () {That.people.remov
E (this);
}});
}; The object of the remove is the entire Li tag, which is the parent of the a tag.
The actual execution is ListModel.people.remove (a.parent) this.removepeople = function () {that.people.remove (this);}; Ko.applybindings (New Listmodel ());
It is easy to confuse the relationship between the DOM node and the ViewModel hierarchy. First, apply a foreach binding on the UL, i.e. each Li corresponds to each people subkey. This corresponds to the following, according to JS scope rules to understand. When it comes to scopes, we have to mention this, which is what I'm supposed to be like first love, this pit I times. Here the eggplant in the official version added a remove function, and the official removepeople corresponding to see the simple. As for $index, $parent these variables, literally.
Interaction Class Properties
Finally to the point, the most important reason to use KO is to handle the dynamic interactive UI presentation problem, which focuses on some of the bindings related to the form.
(1) Click Binding
Syntax: data-bind= "Click:clickhandler", where the ClickHandler function can be any function, not necessarily if the function in ViewModel, as long as can be referred to. There are a few things to note about the Click event:
1. Parameter passing, KO by default, the current component is passed as the first parameter to the ClickHandler function, where you notice the current binding context, for example, in the with environment, the returned component becomes the with component rather than the current component you want. If you also need to pass the event argument, the event is passed as the second argument. If you need to pass in more parameters, you need to wrap it up with a function. Such as:
<button data-bind= "click:function (data, event) {myfunction (' param1 ', ' param2 ', Data, Event)}" >
click me
2. Default behavior settings (such as links)
Ko default is to prohibit the default event behavior, and usually we do not have the link to the point of attack event to let it jump. But if you have to open it, just return true in ClickHandler.
3. Bubbling
Ko default is allowed to bubble, you can data-bind= "Click:clickhandler, Clickbubble:false" To set the click event does not bubble.
(2) Event binding
KO provides this interface for users to customize binding events. About parameter passing, default behavior, bubbling, and so on, and the click Binding is the same, using the case:
<div>
<div data-bind= "event: {mouseover:enabledetails, mouseout:disabledetails}" >
Mouse over Me
</div>
<div data-bind= "visible:detailsenabled" >
Details
</div>
</div >
<script type= "Text/javascript" >
var viewModel = {
detailsEnabled:ko.observable (false),
enabledetails:function () {
this.detailsenabled (true);
},
disabledetails:function () {
This.detailsenabled (FALSE);
}
;
Ko.applybindings (ViewModel);
(3) Submit binding
Mainly used to do some validation of the form of work. Ko blocks the default submit form action and goes into a function that is bound by submit. Return true in the binding event when subsequent submissions are required.
PS: Why not use the Click event in the form to handle it? Because submit is designed to handle the submission of events, it can also accept a carriage return type of submit action, but click Not.
(4) Value and TextInput binding
Binding value and TextInput in the input box look the same, but it is more recommended to bind using the TextInput event because TextInput is a new addition to handling input events. As you can see in the previous article, when you enter a value binding (left), you must remove the focus from the input box before updating it, and textInput (right) is immediately updated.
Although the value binding can also achieve the same effect as textInput by setting data-bind= "{value:price, valueupdate: ' Afterkeydown '}", this compatibility in the browser is not as TextInput good.
(5) Options binding (Selectedoptions)
You can use the options to bind the values of children in a drop-down list, which can be either a string or a JS object. The previous ("Knockoutjs Learning Experience Journey" (1) KO early experience) shows a string, this time to pass an object:
Code:
<p>your Country: <select data-bind= "options:availablecountries, OptionsText: ' CountryName ', Value:selectedcountry, optionscaption: ' Choose ... ' "></select> </p> <div data-bind=" Visible:selectedcountry "> <!--appears when you select something--> to have chosen a country with population & Lt;span data-bind= "Text:selectedcountry" ()?
Selectedcountry (). Countrypopulation: ' Unknown ' ></span> </div> <script type= "Text/javascript" >//constructor for a object with two properties var Country = function (Name, population)
{this.countryname = name; this.countrypopulation = population;}; var ViewModel = {AvailableCountries:ko.observableArray ([New Country ("UK", 65000000), New Country ("USA", 320000000), new
Country ("Sweden", 29000000)), selectedCountry:ko.observable ()//Nothing selected by default};
Ko.applybindings (ViewModel); </script>
The option to bind the list box is used here, and the item is selected using value binding. Because the option is a JS object, you use a optiontext to specify the display in the list box. Optioncaption refers to the default display value when no item is selected. If we set a multiple-selection list box, then we can't bind the selected item with value, and use the selectoptions to bind the selected item.
(6) Other bindings: enable/disable, Hasfocus, checked, UniqueName.
These events are very simple to use and are not specifically described. The last UniqueName is used to set the unique Name property of the form control, which is not committed to the background when it is submitted to the background in the form, so it has a binding function. The official website about Hasfoucus also has a more commonly used effect:
Name:
Name:bert Bertington
Click the name to edit it; Click elsewhere to apply changes.
Click on the name can become editable, lose focus and become normal text, this effect with KO to achieve quite simple.
Summarize
This article mainly introduces the use of various bindings in Knockoutjs , the combination of these binding methods can simply do a need for more dynamic interaction UI page. The important thing to use these methods is to remember that the binding is a function object, so you can operate directly inside the HTML, so that sometimes the JS code structure can be simpler.
Official Tutorials: http://knockoutjs.com/documentation/introduction.html