Javascript 多个选择列表和KnockoutJS
我在KO站点上实现了一个多选列表。我的代码的重要部分目前看起来像这样:Javascript 多个选择列表和KnockoutJS,javascript,knockout.js,Javascript,Knockout.js,我在KO站点上实现了一个多选列表。我的代码的重要部分目前看起来像这样: function Attribute(data) { var self = this; self.Id = data.Id; self.Name = data.Name; } // Individual Row in Table function Criteria(data) { var self = this; self.Attributes = data.Attributes;
function Attribute(data) {
var self = this;
self.Id = data.Id;
self.Name = data.Name;
}
// Individual Row in Table
function Criteria(data) {
var self = this;
self.Attributes = data.Attributes;
}
// Represent the ViewModel for attributes.
function CriteriaViewModel() {
var self = this;
// Catalog Data
self.availableAttributes = window.ko.observableArray([]);
$.getJSON(window.attributeListUrl, function(availableData) {
self.availableAttributes($.map(availableData.Attributes, function(item) { return new Attribute(item); }));
});
// Editable Data
self.criterion = window.ko.observableArray([]);
// Load initial state from server
$.getJSON(window.criteriaListUrl, function (availableData) {
self.criterion($.map(availableData.Criterion, function (item) { return new Criteria(item); }));
});
}
然后,在我的HTML中,我将所有内容绑定在一起,或者,我至少尝试:
<tbody data-bind="foreach: criterion">
<tr>
<td>
<select class="selectedAttributes"
data-bind="options: $root.availableAttributes, selectedOptions: Attributes, optionsText: 'Name', optionsValue: 'Id'"
multiple
size="6">
</select>
</td>
</tr>
</tbody>
可能的选项显示正确。但是,标准的属性与可能的选项之间没有明显的绑定。从阅读指南来看,似乎KO应该能够直接绑定对象。这里有人能提供指导吗
我忘了提到,除了multi-select列表的实际绑定之外,其他一切都可以工作。一般来说,我正在适当地应用绑定—只是没有使用多选列表。Criteria对象上的attributes属性需要是observableArray。这是一个
Criteria对象上的attributes属性需要是observableArray。这是一个 var x=$'select1选项:selected'; 如果x.长度>0{ x、 每个函数{ 警报$this.text; self.selectedCategory.pushnew categoryModel$this.text; $选择1选项:已选择。删除; }; } var x=$'select1选项:selected'; 如果x.长度>0{ x、 每个函数{ 警报$this.text; self.selectedCategory.pushnew categoryModel$this.text; $选择1选项:已选择。删除; };
}“selectedOptions”绑定的主要参数应该是数组或可观察数组。此数组将包含选定的值。我希望看到像self.chosenAttributes=window.ko.observableArray[]这样的东西;“selectedOptions”绑定的主要参数应该是数组或可观察数组。此数组将包含选定的值。我希望看到像self.chosenAttributes=window.ko.observableArray[]这样的东西;我还没有尝试过,但我看到的唯一不同之处是,Criteria Attributes属性是一个属性对象数组,而不仅仅是一个属性ID数组。这会有所不同吗?还是同样的原则仍然适用?工作得很好。我很好奇为什么对象数组没有映射,而ID数组映射得很好。根据KO.js文档,对象应该正确映射。如果您有任何其他见解,我们将不胜感激。再次感谢!我还没有尝试过,但我看到的唯一不同之处是,Criteria Attributes属性是一个属性对象数组,而不仅仅是一个属性ID数组。这会有所不同吗?还是同样的原则仍然适用?工作得很好。我很好奇为什么对象数组没有映射,而ID数组映射得很好。根据KO.js文档,对象应该正确映射。如果您有任何其他见解,我们将不胜感激。再次感谢!你能至少解释一下为什么你的解决方案比已经被接受的答案好吗?你能至少解释一下为什么你的解决方案比已经被接受的答案好吗?
function Criteria(data) {
var self = this;
self.Attributes = ko.observableArray(data.Attributes);
}