【问题标题】:Knockout Mapping Issue淘汰赛映射问题
【发布时间】:2015-03-30 04:21:45
【问题描述】:

我是 Ko 和地图插件的新手。

我必须从http://api.openweathermap.org/data/2.5/history/city?q=Vancouver,%20ca读取一个城市的天气api数据

并使用 ko 和映射将其显示在 UI 中。

但是我在映射时遇到了问题,因为数据没有出现在 UI 中。

ko.mapping.fromJS(models, self.ArrayOfModels);
http://jsfiddle.net/balain/ENMGp/536/

提前谢谢你。

【问题讨论】:

  • ko.mapping.fromJS(models, {}, self.ArrayOfModels);
  • 感谢托马拉克的帮助。但是数据仍然没有出现在 UI 中。
    我是在数据绑定中做错了什么。你能看看我的小提琴吗

标签: knockout.js knockout-2.0 knockout-mapping-plugin


【解决方案1】:

首先,your fiddle 使用了真正过时版本的淘汰赛(1.2.1 是古老的)。我已将其更新为 3.2.0。此外,您不需要任何 jQuery 模板插件。我已经删除了。

接下来,我建议您构建视图模型以使其能够自行处理,包括从初始化数据引导。像这样:

// Contained Model
function SearchResultModel(init) {
    // data
    this.message = ko.observable();
    this.cod = ko.observable();
    this.city_id = ko.observable();
    this.calctime = ko.observable();
    this.cnt = ko.observable();
    this.list = ko.observableArray();

    // init
    ko.mapping.fromJS(init, {}, this);
}

接下来,您可以稍微压缩您的 Ajax 请求:

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

    // data
    self.city = ko.observable();
    self.searchResult = ko.observable(new SearchResultModel());

    // methods
    self.getWeatherByCity = function () {
        var city = self.city()
        if (city) {
            $.get('http://api.openweathermap.org/data/2.5/history/city', {
                q: city
            }).done(function(data) {
                self.searchResult(new SearchResultModel(data));
            }).fail(function () {
                alert("could not get weather data!");
            });
        } else {
            // no city? => empty the search result
            self.searchResult(new SearchResultModel());
        }
    };

    // init
    ko.mapping.fromJS(init, {}, self);
}

使用示例数据初始化:

ko.applyBindings(new WeatherViewModel({
    city: "Vancouver, CA"
}));

你很高兴:http://jsfiddle.net/ENMGp/539/

既然你标记了这个 [knockout-2.0](我不知道你为什么要在一个新项目中使用它),我已经创建了一个 2.0 兼容版本:http://jsfiddle.net/ENMGp/540/。代码是相同的,但淘汰赛 2.0 不适用于 jQuery 1.9+,所以我不得不降级这两个库。 FWIW,我建议使用当前版本的淘汰赛。

【讨论】:

    【解决方案2】:

    http://jsfiddle.net/ybo0zrwh/

    this.SuccessfullyRetrievedModelsFromAjax = function(models) {
        self.ArrayOfModels.push(ko.mapping.fromJS(models));
    };
    

    您似乎没有从服务器获取对象数组。您可以映射单个对象,然后将其推送到您的可观察数组中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-05
      • 2013-05-27
      • 2012-10-03
      • 2012-06-08
      • 1970-01-01
      • 2012-12-05
      • 2017-07-07
      • 2014-03-26
      相关资源
      最近更新 更多