Use knockout to bind a simple JSON object

Source: Internet
Author: User

Recently, Ko's Js framework seems to be on fire, so I simply learned the reference in the garden.Article:

Http://www.cnblogs.com/n-pei/archive/2011/12/23/2299217.html

Uncle Tom's blog knockout Series

For convenience, we have made uncle's series of articles into CHM. If you need them, please go to the transfer point.

 

Bind Object Data

 

HTML form:

 
<Form ID = "xxoo"> name: <input type = "text" data-bind = "value: truename" name = "truename" id = "txttruename"/> Email: <input type = "text" data-bind = "value: email" name = "email" id = "txtemail"/> </form>

There are many other attributes, so I won't skip them here ~~~

 

JS Code:

To use Ko for data binding, you must construct an object suitable for Ko. The method is as follows:

 
VaR viewmodel = {truename: KO. observable ("Crazy talent"), email: KO. objservable ('2017 @ QQ.com ')}

Of course, we are at the backendCodeYou can also generate such JSON. If it is not related to the back-end writeProgram, Using JSON. Net to generate a JSON object does not match Ko. So

We need to construct an object in JS at the front end into an object suitable for Ko. You can write it as shown above, but it is annoying if there are many attributes, so we can write a general method.

Practice:

 
Function binddata (modelobj) {If (modelobj) {var viewmodel ={}; for (VAR item in modelobj) {viewmodel [item] = Ko. observable (modelobj [item]);} Ko. applybindings (viewmodel );}}

That's all. I'm not afraid of any attributes you have ~~, Write it in one way! Effort-saving!

The above method may have problems with your logic. You can make some modifications. This should be hard for you. I am optimistic about you!

 

Yes, I forgot to say that I should first introduce knockout. js. This can be downloaded on the homepage of the official website.

 

 

 

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.