绑定到knockoutJS中的可观察数组的问题

时间:2014-08-08 00:51:36

标签: javascript jquery arrays knockout.js ko.observablearray

我目前在将数据绑定到knockoutJS中的可观察数组时遇到问题。我要做的是根据用户从选择框中选择的内容显示新值。

小提琴可在http://jsfiddle.net/jwayne2978/k0coh1fz/3/

获得

我的HTML如下所示。

<select data-bind="options: categories, 
    optionsText: 'name',
    optionsValue: 'id',
    value: selectedCategory,
    optionsCaption: 'Choose...',
    event: { change: categoryChanged }
    ">
<div data-bind="foreach: values">
    <div data-bind="text: name"></div>
</div>
<div data-bind="foreach: categories">
    <div data-bind="text: name"></div>
</div>

我的JavaScript如下所示。

var categories = [
    { "name" : "color", "id": "1" },
    { "name" : "names", "id": "2" }
];
var values0 = [ { "name" : "empty1" }, { "name" : "empty2" } ];
var values1 = [ { "name" : "white" }, { "name" : "black" } ];
var values2 = [ { "name" : "john" }, { "name" : "name" } ];
var Category = function(data) {
    this.name = ko.observable(data.name);
    this.id =  ko.observable(data.id);
};
var Value = function(data) {
    this.name = ko.observable(data.name);
}
var ViewModel = function(categories, values) {
    var self = this;
    self.categories = ko.observableArray(ko.utils.arrayMap(categories, function(category) {
        return new Category(category);
    }));
    self.selectedCategory = ko.observable();
    self.values = ko.observableArray(ko.utils.arrayMap(values, function(value) {
        return new Value(value);
    }));
    self.categoryChanged = function(obj, event) {
        if(self.selectedCategory()) {
            console.log(self.selectedCategory());
            if("1" == self.selectedCategory()) {
                //console.log(values1);
                self.values.push(new Value({"name":"test1"}));
            } else if("2" == self.selectedCategory()) {
                //console.log(values2);
                self.values.push(new Value({"name":"test2"}));
            }
        }
    };
};
var viewModel;
$(document).ready(function() { 
    viewModel = new ViewModel(categories, values0);
    ko.applyBindings(viewModel);
});

当一个类别被改变时,我真正想要做的就是这样。

self.values.removeAll();
for(var v in values1) {
 self.values.push(new Value(v));
}

但是这不起作用,所以我只需要用一行来将一个新值推入可观察数组。

此外,我对valuescategories的div的迭代没有显示,我不确定原因。

对我做错了什么的想法?

1 个答案:

答案 0 :(得分:2)

您的<select>元素缺少结束标记,导致视图中的问题进一步缩小。

<select data-bind="options: categories, 
    optionsText: 'name',
    optionsValue: 'id',
    value: selectedCategory,
    optionsCaption: 'Choose...',
    event: { change: categoryChanged }"></select>

更新小提琴:http://jsfiddle.net/ragnarok56/69q8xmrp/