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