foreach:绑定无效 ko.mapping.fromJS 数据

foreach: binding not working ko.mapping.fromJS data

我正在尝试使用 ko.mapping.fromJS 显示我从 JSON 请求(见下文)中获得的工作列表(使用 foreach),但它显示为空白.. JSON 数据似乎已正确加载到 observables 数组中,但未在 HTML 中呈现????

这实际上是移动网络应用程序(Jquery 移动)的一部分,因此数据出现在第二页上,不确定这是否有影响(我在开头加载了所有代码)

HTML(简体)

<ul  data-bind="foreach: JobsToday " >
 <li>   <span data-bind="text: job_id"> </span>   </li>
 </ul>

JSON 数据(简体)

[{"job_id":"1753","driver_id":"23"},{"job_id":"1754","driver_id":"23"}]

JAVASCRIPT

    <script type="text/javascript">
    var JobsToday=ko.observableArray([]);  // observable array holds the jobs  for the current day  

 function DispatchModel(){

    self = this;  //cache the current context
    self.userd_id= 0;

        $.getJSON(controller_php_script+"/",  {'action' : 'list_driver_jobs', 'driver_id' : self.user_id}, function(jobsData) 
        {

     self.JobsModelArray= ko.mapping.fromJS(jobsData); // get the jobs
         JobsToday =self.JobsModelArray;  //assign to global observable

 //print out the observablbles to make sure data is three
      console.log( " JobsModelArray: "+   ko.toJSON( JobsToday ) );  
                });

} //end of DispatchModel


// Start of our  main function 
$(document).ready(function () {

    var vm = new DispatchModel();   //create the Dispatch VMM
    ko.applyBindings(vm);  //knockout.js apply the binding

});  //end $(document).ready

    </script>

JobsToday 可观察数组在视图模型函数之外。由于您将表单绑定到 DisplayModel,因此无法绑定到。将 JobsToday 移到函数内部。

 function DispatchModel(){

    self = this;  //cache the current context
    self.JobsToday=ko.observableArray([]);  // observable array holds the jobs  for the current day  

第二个问题是您将 JobsToday 设置为您映射的数据。这是 Knockout 初学者的常见错误。您通过函数设置可观察对象,而不是直接设置。这样效果会更好:

var mapped = ko.mapping.fromJS(jobsData); // get the jobs
self.JobsToday(mapped);  //assign to observableArray