Knockoutjs Learning Note 08: Form field Bindings

Source: Internet
Author: User

The previous bindings are all used on the Basic tab, which mainly deals with the binding of the form field labels.

One, value binding

Binding Tags: input text, textarea.

    <p> Username: <input type= "text" data-bind= "Value:name"/><span data-bind= "Text:name" ></span>< /p>    <p> Password: <input type= "text" data-bind= "Value:password"/><span data-bind= "Text:password" ></span></p>    function UserInfo () {        var = this;        Self.name = ko.observable ("Tom");        Self.password = ko.observable ("123456");    }    var userInfo = new UserInfo ();    Ko.applybindings (UserInfo);

There is also a parameter about value: Valueupdate, which sets the timing for triggering the binding. The following values are supported:

"Change" (default)-updates the value of the view model when the focus is lost, or when the <select> element is selected.

"KeyUp" – updates the view model as soon as the user finishes typing a character.

"KeyPress" – Update the view model immediately when the user is tapping a character but does not release the keyboard. Unlike KeyUp, this update is the same as KeyDown.

"Afterkeydown" – Updates the view model when the user starts typing characters. The main thing is to capture the browser's KeyDown event or asynchronous handle event.

With these options, using "Afterkeydown" is the best option if you want to update your view model in real time.

For example, I can change the user name edit box above to: <input type= "text" data-bind= "value:name,valueupdate: ' Afterkeydown '"/> so that it can be updated in real time.

Ii. Options Binding

Binding Tags: SELECT.

Example 1:options specifies the set of items.

<select data-bind= "Options:items" ></select>var items = ["Item1", "item2", "Item3"];ko.applybindings ( items);//Add New Item Items.push ("Item4");

Example 2:optionstext: Specifies the name of the property to display; Optionscaption: initial option; value: the selected item.

    <select data-bind= "Options:items,optionstext: ' Name ', optionscaption: ' Please select ... ', Value:selectedvalue" ></ select>    <div data-bind= "Text:selectedvalue () SelectedValue (). Name: ' Not selected ' ' ></div>    var data = {        Items:ko.observableArray ([{Name: "China", Rank:1},{name: "United States", Rank:2},{name: "Russia", Rank:3}]),        SelectedValue : Ko.observable ()            }    ko.applybindings (data);

Third, selectedoptions binding

Binding Tags: multiple select

    <select data-bind= "Options:items,selectedoptions:selecteditems" multiple= "multiple" size= "5" ></select >    <div data-bind= "Text:selecteditems (). Join (', ')" ></div>    var data = {        items: Ko.observablearray (["China", "United States", "Russia"]),        selectedItems:ko.observableArray (["China"])         }    ko.applybindings (data);

Selectedoptions represents the selected item. Selectedoptions can support not only strings, but also object types like options.

Iv. Checked binding

Binding Tags: radio, checkbox.

Example 1, the radio of the same checked property is a group.

    <input type= "Radio" value= "basketball" data-bind= "Checked:sport"/> Basketball    <input type= "Radio" value= " Football "data-bind=" Checked:sport "/> Soccer    <input type=" Radio "value=" Running "data-bind=" Checked:sport "/ > Running    <p> your choice: <span data-bind= "Text:getsport ()" </p>    var data = {        sport:ko.observable (" Basketball "),        getsport:function () {            switch (Data.sport ()) {case                " basketball ":                    return" basketball ";                Case "Football":                    return "football";                Case "Running":                    return "Running";                Default:                    return "temporarily none";    }}} Ko.applybindings (data);

Example 2:checked can be chosen more, so use Observablearray.

    <input type= "checkbox" value= "basketball" data-bind= "Checked:sport"/> Basketball    <input type= "checkbox" Value= " Football "data-bind=" Checked:sport "/> Soccer    <input type=" checkbox "value=" Running "data-bind=" Checked:sport " /> Running    <p> your choice: <span data-bind= "Text:getsport ()" </p>    var data = {        sport: Ko.observablearray (["Basketball", "football", "running"]),        getsport:function () {                var sports = Data.sport ();                if (!sports) {                    return "temporarily none";                }                Return Sports.join (",");                    }    }    Ko.applybindings (data);

V. Enable binding/disable Binding

Sets the disabled property of input based on the result. The two roles are the same.

    <input type= "text" data-bind= "enable:isenabled"/><br/> <input    type= "button" value= "Test" data-bind= "disable:isdisabled"/>

Vi. Hasfocus Binding

Gets the focus when the result is true. Input text is used more.

VII. Click and submit Binding

Bind the fixed-point and commit events.

Example 1: The first parameter of the function is the event object.

    <input type= "button" value= "click" data-bind= "Click:btnclick"/>    var data = {        Btnclick:function (event) {            Console.log (event);        }    }    Ko.applybindings (data);

Example 2: The event bubbling is canceled, and event bubbling can be canceled by binding cancelbubble:false.

    <div data-bind= "Click:btnclick" >        <input type= "button" value= "click" data-bind= "Click:btnclick, Clickbubble:false "/>    </div>

Example 3: You can also pass parameters to the execution function in the binding event, the simplest way is to wrap it with an anonymous function.

    <div data-bind= "Click:btnclick" >        <input type= "button" value= "click" data-bind= "Click:function () { Btnclick (' parameter 1 ', ' parameter 2 ');} " />    </div>

Example 4:submit is bound to the form label, and the form is only submitted when the binding function return ture. And why does the table use the submit binding instead of the normal click binding? Because there are more actions for form binding, such as pressing ENTER to trigger a commit operation.

    <form action= "default.aspx" data-bind= "Submit:submitform" >        <input type= "text" name= "name"/>        <input type= "Submit"/>    </form>    var data = {        submitform:function () {            return true;        }    }

Viii. Event Binding

In addition to clicking Events, KO also supports bindings for other events. For example: KeyPress, MouseOver, mouseout and so on.

    <div style= "width:100px;height:100px;background:red;" data-bind= "Event:{mouseover:divmouseover,mouseout: Divmouseleave} "></div>    <div data-bind=" Text:status "></div>    var data = {        Divmouseover:function (event) {            this.status ("over");        },        divmouseleave:function (event) {            This.status ("Out");}        ,        status:ko.observable ("not Started")    }    ko.applybindings (data);

Ix. Summary

Ko not only supports style binding, but also supports event binding and data as the core, we only need to focus on data changes and logical operation of data, which greatly improve our development efficiency.

Knockoutjs Learning Note 08: Form field Bindings

Related Article

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.