0

我的任务是对 KnockoutJS 进行 POC,但遇到了一个我无法弄清楚的问题。

我想使用 Ajax 从服务中检索数据,然后使用 ko.mapping.fromJS() 填充表单。当我从 ajax 调用的成功函数中调用映射时,我的表单不会填充。如果我将它移到成功之外,那么它可以正常工作。

更新:我确实知道在我的 jsfiddle 中确实调用了 load 函数(在里面放了一个警报,它确实触发了),但是表单没有填充..

http://jsfiddle.net/Ud9ex/6/

var planDesignData = {
        RecordID: '1124',
        Name: "Main"            
    };


var PlanDesignModel = function () {
var self = this;            

//*** As soon as I move this line inside the sucess the input doesn't get populated 
self.planDesign = ko.mapping.fromJS(planDesignData);

self.load = function () {
    $.ajax({
        type: "POST",
        url: "/echo/json/",
        contentType: "application/json; charset=utf-8",
        dataType: "json",                    
        success: function (data) {                       
            var loadedPD = {};

            //I want to run the mapping here

        }
    });
}
}


$(document).ready(function () {
            var viewModel = new PlanDesignModel();
            viewModel.load();
            ko.applyBindings(viewModel);    

        });

任何帮助将不胜感激。

4

1 回答 1

-2

这是示例

您需要做的就是将数据发送到/echo/json.

defer我在这个例子中做了一个:

$(document).ready(function () {
    var viewModel = new PlanDesignModel();
    $.when(viewModel.load).always(function(){
        ko.applyBindings(viewModel);
    });
});

但一切正常:

success: function (data) {
            var loadedPD = {};
            console.log(data);
            self.planDesign = ko.mapping.fromJS(planDesignData);
            //I want to run the mapping here

        }

注意,我确实延迟了 1 秒:

data: {
            json: JSON.stringify({
                RecordID: '1124',
                Name: "Main"
            }),
            delay: 1
        },
于 2013-11-10T16:10:49.577 回答