knockout observable将一些对象添加到api返回的输出顶部的可观察数组

时间:2016-05-23 15:37:52

标签: javascript jquery knockout.js

_self.CITIES = ko.observableArray([]);

        m_usp_doc.on("click", "#citySelection", function () {
            $.ajax({
                type: 'GET',
                url: '/webapi/api/?',
                dataType: 'json',
                context: this,
                success: function (jsonData) {
                    _self.CITIES(jsonData);
                    _self.CITIES.push({ "a": "A", "b": "B" }) ;
                }
            });

api返回一些输出值,如'F','G',H'

我希望从api获取此数据并将硬编码"A", "B", "C", "D", "E"推送到其上方。

因此该模型具有"A", "B", "C", "D", "E", 'F', 'G', 'H'

我使用_self.CITIES.push()进行了尝试,并在声明可观察但没有效果的情况下声明了这些(AE

任何人都可以告诉我该怎么做?

1 个答案:

答案 0 :(得分:0)

您可以创建单独的项目View模型,然后在每次获得新对象时创建该模型的新实例。另外如果您想在数组前面添加它们,可以使用unshift()而不是推()。
示例:https://jsfiddle.net/9aLvd3uw/130/

var MainViewModel = function () {
   var _self = this;
   _self.CITIES = ko.observableArray([]);
   _self.CITIES.push(new ItemViewModel({ "a": "F", "b": "G" ,"c": "H" , "d" : "I" , "e" : "j"}));

   self.ClickMe = function (){
     _self.CITIES.unshift(new ItemViewModel({ "a": "A", "b": "B" ,"c": "C" , "d" : "D" , "e" : "E"}));
   }
}

var ItemViewModel = function (data) {
  var _self = this;
  _self.Variable1 = ko.observable(data.a);
  _self.Variable2 = ko.observable(data.b);
  _self.Variable3 = ko.observable(data.c);
  _self.Variable4 = ko.observable(data.d);
  _self.Variable5 = ko.observable(data.e);
}
 ko.applyBindings(MainViewModel);