Knockoutjs 3.X API Fourth Chapter form TextInput, Hasfocus, checked binding _javascript Tips

Source: Internet
Author: User

TextInput Binding Purpose

TextInput bindings are used primarily for <input> or <textarea> elements. He provides a two-way update of Dom and ViewModel. Unlike the value binding, TextInput bindings are updated in real time.

For example:

Source:

<p>login Name: <input data-bind= "Textinput:username"/></p> <p>password
: <input type= "Password" data-bind= "Textinput:userpassword"/></p>

ViewModel:

<pre data-bind= "Text:ko.toJSON ($root, NULL, 2)" ></pre>
<script>
ko.applybindings ({
UserName:ko.observable (""),//initially blank
userPassword:ko.observable ("abc")//Prepopulate
});
</script>

Note 1:textinput binding VS value Binding

Although value binding can also be combined with bidirectional text box and view model performance, bloggers prefer TextInput because he is updated in real time. The main difference between a value binding and a textinput binding is:

Instant updates

Value by default, your model will not be updated until the user moves the focus away from the text box. TextInput updates the model as soon as you click the key or other text input.

Event handling for browsers

Different browsers have text-entry mechanisms, such as cutting, dragging, or accepting automatic completion of suggested events in different browsers where the mechanism is inconsistent. Value bindings, there are additional options, such as Valueupdate:afterkeydown to get updates to a particular event, but it may not be compatible with all browsers.

The TextInput combination is a different mechanism for dealing with various browsers, even when it is possible to maintain consistency and direct updating of models in response to different text-entry mechanisms.

Do not attempt to bind on the same element using value and TextInput.

Hasfocus Binding Purpose

Hasfocus binding is the focus state binding of a view model property to a DOM element. It is a two-way binding, so:

If your view model property is set to True or FALSE, the related element becomes focused or not focused.
If the user manually focus or unfocuses The associated component, the View model property will be set to TRUE or false accordingly.
If you are building, editing elements dynamically displaying complex forms that you want to control, the user should start typing, or the response position of the caret, which is very useful.

Example 1

In this example, a message is displayed when the text box currently has the focus, and a button is used to programmatically trigger the focus.

Source:

<input data-bind= "hasfocus:isselected" >
<button data-bind= "click:setisselected" >Focus programmatically</button>
<span data-bind= "visible:isselected" >the textbox has focus</span> 
<script>
var viewModel = {
isSelected:ko.observable (false),
setisselected:function () { This.isselected (True)}
;
Ko.applybindings (Viewmodel,document.getelementbyid ("EQ2"));
</script>

Example 2

Because Hasfocus bindings are two-way binding, this makes it easier to switch to edit mode.

Source:

<p>
Name: 
<b data-bind= "visible:!editing (), Text:name, Click:edit" > </b>
<input Data-bind= "visible:editing, Value:name, hasfocus:editing"/>
</p>
<p><em>click the Name to edit it; Click elsewhere to apply changes.</em></p>
<script>
function Personviewmodel (name) {
/ /Data
this.name = ko.observable (name);
This.editing = Ko.observable (false);
Behaviors
This.edit = function () {this.editing (True)}
}
ko.applybindings (New Personviewmodel (" Bert Bertington "), document.getElementById (" eq3 "));
</script>

Checked binding Purpose

Checked bindings are used primarily for check boxes (<input type= ' checkbox ' >) or radio buttons (<input type= ' Radio ' >) and are bound to the view model properties.

This updates the value of your view model property when the user changes the form control. Similarly, when you update the values of your view model, they are also reflected directly on the form control.

Note: For text boxes, Drop-down lists, and all unchecked form controls, you need to use either the value binding or the TextInput binding to read and write the values of the elements, not the checked bindings.

Example 1: check box bindings

Source:

<p>send me spam: <input type= "checkbox" data-bind= "Checked:wantsspam"/></p> <script "type="
Text/javascript ">
var viewModel = {
wantsSpam:ko.observable (true)//initially checked
};
... then later
... Viewmodel.wantsspam (FALSE); The checkbox becomes unchecked
</script>

Example 2: Multiple check boxes with array bindings

Source:

<p>send me spam: <input type= "checkbox" data-bind= "Checked:wantsspam"/></p> <div data-bind=
"Visible:wantsspam" >
preferred flavors of spam:
<div><input type= "checkbox" value= "Cherry" data-bind= "Checked:spamflavors"/> cherry</div>
<div><input type= "checkbox" value= "Almond" data-bind= "Checked:spamflavors"/> almond</div>
<div><input type= "checkbox" Value= "MSG" data-bind= "Checked:spamflavors"/> monosodium glutamate</div>
</div>
<script type= "text/ JavaScript ">
var viewModel = {
wantsSpam:ko.observable (true),
SpamFlavors:ko.observableArray ([" Cherry "," almond "])//initially checks the cherry and Almond checkboxes
};
... then later
... ViewModel.spamFlavors.push ("msg"); Now additionally checks the monosodium glutamate checkbox
</script>

Example 3: Radio button

Source:

<p>send me spam: <input type= "checkbox" data-bind= "Checked:wantsspam"/></p> <div data-bind=
"Visible:wantsspam" >
preferred flavor of spam: <div><input type= "Radio"
name= "Flavorgroup" value = "Cherry" data-bind= "Checked:spamflavor"/> cherry</div> <div><input type= "Radio"
Flavorgroup "value=" Almond "data-bind=" "Checked:spamflavor"/> almond</div> <div><input type=
" Radio "Name=" Flavorgroup "value=" msg "data-bind=" Checked:spamflavor "/> monosodium, glutamate</div>
< /div>
<script type= "Text/javascript" >
var viewModel = {
wantsSpam:ko.observable (true),
SpamFlavor:ko.observable ("almond")//initially selects only the almond button
};
... then later
... Viewmodel.spamflavor ("msg"); Now only monosodium glutamate is checked
</script>

Parameters

Main technical parameter

Ko sets the selected state of the element to match your parameter values. Any previously selected states will be overwritten. The way your arguments are interpreted depends on what type of binding element you are in:

For check boxes, when the value of the parameter is true, Ko is set to the element is selected, and false to the unchecked state. If you are not given a Boolean value, Ko will loosely explain. This means that non-0 numeric and non-null objects and Non-null strings will be interpreted as true, while zeros, null,undefined, and empty strings will be interpreted as false.

When the user selects or uncheck the check box, set KO your model property to TRUE or false.

If your argument is parsed into an array of arrays that are given. In this case, KO sets the check whether the Value property in the DOM matches the array value, if the value match is selected, or if it does not match.

When the user selects or cancels the check box, changes the value of the corresponding view model property to KO. Just like Example 2.

For radio buttons, KO checks whether the value of the view model equals the Value property of the radio button DOM node or whether the view model property values are equal to the values specified by the CheckedValue parameter. Just like Example 3.

When the user changes its radio button, KO sets the value of the Model property value to the selected radio button. As in Example 3, clicking the radio button value= "Cherry" will set Viewmodel.spamflavor to "Cherry".

If your parameter is a monitor attribute type, each time the value changes the binding updates the element's selected state. If the parameter is not a monitor property, it will only set the selected state of the element at the first run and will not be updated later.

Other parameters

CheckedValue

The CheckedValue parameter defines the use of values in conjunction with a checked binding rather than the Value property of an element. This is useful if the value you want is something other than a string (such as an integer or an object), or a value that you want to set dynamically.

For example, the following example:

Source:

<!--ko foreach:items-->
<input type= "checkbox" data-bind= "CheckedValue: $data, checked: $ Root.chosenitems "/>
<span data-bind=" Text:itemname "></span>
<!--/ko-->
< Script type= "Text/javascript" >
var viewModel = {
Items:ko.observableArray ([
{itemname: ' Choice 1 '},< c8/>{itemname: ' Choice 2 '}
],
chosenItems:ko.observableArray ()
};
</script>

If your checkedvalue parameter is a monitoring attribute, the change of the value and whether the element is selected, the binding updates the checked model property. For a check box, it deletes the old value from the array and adds a new value. For radio buttons, it only updates the model values.

The above is a small set to introduce the Knockoutjs 3.X API Fourth chapter of the form TextInput, Hasfocus, checked 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.