如何使用ko.mapping.fromJS从一个Ajax调用填充数据的observableArray?如何使用、数据、ko、fromJS

2023-09-10 17:20:05 作者:[亡魂溺海]

我有一个包含有一个foreach循环一轮的车型阵列模板的视图。然而,模型的数组来自Ajax调用。

I have a view which contains a template that has a foreach to loop round an array of models. However, the array of models comes from an ajax call.

下面是该方案的一个例子:

Here is an example of the scenario:

// Contained Model
function SomeModel() {
    var self = this;
    this.Firstname = ko.observable();
    this.Lastname = ko.observable();
    this.Fullname = ko.dependentObservable(function() {
        return this.Firstname + " " + this.Lastname;
    }, self);
}

// View Model
function SomeViewModel() {
    var self = this;

    this.ArrayOfModels = ko.mapping.fromJS([]);

    this.GetModelsByAjax = function() {
        $.ajax(...);
    };

    this.SuccessfullyRetrievedModelsFromAjax = function(models) {
        ko.mapping.updateFromJS(self.ArrayOfModels, models);
    };
}

ko.applyBindings(new SomeViewModel());

这里的景观:

Here's the View:

<HtmlGuff>
    <div data-bind="template: {name: 'model-template', foreach: ArrayOfModels}"></div>
</HtmlGuff>

// Template
<HtmlGuff>
    <h2 data-bind="text: Fullname">
    <div data-bind="text: Firstname" />
    <div data-bind="text: Lastname" />
</HtmlGuff>

这是从Ajax调用的JSON结果:

And this is the json result from the ajax call:

[{
    "Firstname": "Joe",
    "Lastname": "Blogs"
}, {
    "Firstname": "Foo",
    "Lastname": "Bar"
}]

目前我只是路过的 [] 的模型声明,但我不断收到以下错误:

Currently I am just passing in [] to the model declaration, however I keep getting the following error:

名字没有被定义

它打破了这个:返回新功能(jQuery的,$项目,身体);

有没有办法做我想做什么?

Is there any way to do what I want to?

推荐答案

你所要做的,似乎没什么问题。

What you are trying to do seems fine to me.

下面是它的样本工作: http://jsfiddle.net/rniemeyer/ENMGp/你也许可以尝试对调和。

Here is a sample with it working: http://jsfiddle.net/rniemeyer/ENMGp/ that you could maybe try to reconcile against.

我不知道到底是什么你的模型的样子回来从你的AJAX调用不过。

I don't know exactly what your "models" look like coming back from your AJAX call though.

这些线都缺少一个 = ,但我相信这只是一个打字错误,并不会导致你列出的错误。

These lines are missing an =, but I assume that is just a typing error and would not result in the error that you listed.

<div data-bind"text: Firstname" />
<div data-bind"text: Lastname" />

我觉得你最好的选择是做对模型的一些日志记录由Web服务返回,并确保没有嵌套的方式,你不希望他们。

I think that your best bet would be to do some logging on the models being returned by your web service and make sure that they are not nested in a way that you are not expecting.

会很乐意继续帮助,如果你对你的AJAX调用或任何其他线索的结果的详细信息。

Would be happy to continue helping, if you have more info on the result of your AJAX call or any other clues.