Resolves an issue where KO mapping arrays cannot add new objects

Source: Internet
Author: User

This two-day page templating process somewhat slowed down, using KO mapping plug-in situation more up.
The problem that the team members often ask is that when adding new objects to the KO mapping array, the error of the method cannot be found ;
An array created with Ko.observablearray can add or remove objects at will, which is a wonderful problem.
Well, anyway, there's always a problem to be solved.

// Array Definition var Viewmodelarray = Ko.mapping.fromJS ([]);
<!-- Binding Text  - <  data-bind= "foreach: $data">    <data-bind  = "Text:name (). substr (0,5), attr:{' ID ': id}"></li> </ ul >

Once the above definition is complete, page loading and binding can be performed.

$ (function  () {    ko.applybindings (Viewmodelarray, UL);});

Once the UL has been created, an event triggers the Add action, which requires the creation of a new Li object based on the data to be added to the UL, for example:

function Add () {    var data = {Id: $ (' #txtId '). Val (), Name: $ (' #txtName '). Val ()};     // There may be an error "Method not found" here. }

It's been a while. debugging found that because the Name property needs to be special processing, the binding text using name () to read the value of name, and the addition of data in the method is a normal JS object, does not have the properties of the Ko object method, so there is no way to find a method error.
Workaround:

1, in the background processing the Name property, the front bound text as far as possible do not use the property method.

2. The data in the Add method is processed as a Ko object and added.

function Add () {    var data = {Id: $ (' #txtId '). Val (), Name: $ (' #txtName '). Val ()};    Viewmodelarray.push (Ko.mapping.formJS (data));}

The second approach is recommended.

Reprint please indicate the blog from the Flying Dust.

Resolves an issue where KO mapping arrays cannot add new objects

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.