foreach:绑定不起作用ko.mapping.fromJS数据

时间:2015-01-29 22:23:34

标签: javascript knockout.js

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

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

HTML(简化)

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

JSON DATA(简化)

[{"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>

1 个答案:

答案 0 :(得分:2)

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中初学者的常见错误。您可以通过函数设置observable,而不是直接设置。它会更好地工作:

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