Knockout - 如何使用新值重置Dynamic observable数组

时间:2015-06-04 07:49:10

标签: javascript knockout.js lazy-loading observablecollection

我无法使用一些延迟加载Technic来重置具有新值的可观察数组。 我可以清除但无法重置,但它不允许我添加新的动态值。

拨弄 http://jsfiddle.net/kspxa8as/

JS

var i = 1;
            optionsProvider = function(self) {
                var self = self || {};
                self.options = {};
                self.get = function(name, initialValue) {
                    if (!self.options[name]) {
                        console.log("Called - " + name);
                        self.options[name] = ko.observableArray([initialValue]);
                        var requestHeader = '';
                        setTimeout(function() {
                            var aa = [{name: "plant 1" + i, selected: true}, {name: "palnt 2" + i, selected: false}];
                            self.options[name](aa);
                            i++;
                        }, 2000);
                    }
                    return self.options[name];
                };
                return self;
            };
            ViewModel = function() {
                var self = this;
                var k = 1;
                var ob = new optionsProvider(self);
                self.PlantSelected = ob.get("name" + k, '');
                self.fillNewSelect = function() {
                    self.PlantSelected.removeAll();
                    self.PlantSelected().push(ob.get("name" + k, ''));
                    k++;
                };
            };
            ko.applyBindings(new ViewModel());

HTML

<select class="n_imported_country"                     
            data-bind="options: PlantSelected,
                               optionsText :'name'   
            "
            >
    </select>
    <div data-bind="click: function(){
         $root.fillNewSelect();
    }">click to fill new select value</div>

我是淘汰赛的新手,非常欢迎你的回答。

2 个答案:

答案 0 :(得分:1)

我建议使用promise库来处理新项目的异步Ajax加载。我在下面的示例中使用了jQuery的实现。请注意optionsProvider不再需要依赖于viewmodel。

var optionsProvider = function (name, initialValue) {
    return function () {
        return $.get("/target/url", {parameter: "value"})
        .fail(function () {
            console.log("request to get new items failed", arguments);
        });
    };
};

var ViewModel = function () {
    var self = this,
        k = 1,
        ob = optionsProvider("name" + k, '');

    self.PlantSelected = ko.observableArray([]);
    self.fillNewSelect = function () {
        ob().then(function (newData) {
            var p = self.PlantSelected;
            p.removeAll();
            p.push.apply(p, newData);
        });
    };

    // init
    self.fillNewSelect();
};
ko.applyBindings(new ViewModel());

要提到的第二个变化是将新对象推入数组的方法。 .push()支持参数列表:

arr.push('a', 'b', 'c')

如果你想要推送一个项目数组(例如JSON结果),你可以使用.apply(),否则你将推送数组本身作为第一项:

arr.push.apply(arr, ['a', 'b', 'c']);

knockout中的可观察数组支持相同的用法。

比较:http://jsfiddle.net/kspxa8as/6/

答案 1 :(得分:0)

尝试类似这样的技巧这里是将observableArray的实例传递给函数并完成我们的工作

<强>视图模型:

 var  ViewModel = function() {
        var self = this;
        var k = 1;
        var ob = new optionsProvider(self);
        self.PlantSelected = ko.observableArray(); //Declare it as observableArray
        ob.get("name" + k, '',self.PlantSelected) // call the function passing observableArray instance 
        self.fillNewSelect = function() 
        {
          self.PlantSelected.removeAll();
          ob.get("name", ''+ k,self.PlantSelected)
           k++;
        };
  };
 ko.applyBindings(new ViewModel());

功能:

  var i = 1;
  optionsProvider = function(self) {
      var self = self || {};
        self.options = {};
          self.get = function(name, initialValue,instance) { //pass observableArray instance here
          if (!self.options[name] || self.options[name]()) {
            var requestHeader = '';

            setTimeout(function() {
            var aa = [{name: "plant 1" + i, selected: true}, 
                      {name: "palnt 2" + i, selected: false}];
                   instance(aa); // assign data to instance 
             },2000);
          i++;
       }
    return true;      
   };
  return self;
};

工作样本 here