【发布时间】:2014-01-17 10:03:43
【问题描述】:
我正在尝试自动更新属于 Text 对象的 3 个“标签”字段(“ManagerTags”、“EmployeeTags”、“LocationTags”)。 每个标签字段都是来自 Tags=ko.observableArray() 的过滤数组。
这是文本对象:
var Textbatch = function (data) {
var self = this;
self.TextbatchId = data.TextbatchId;
self.Title = ko.observable(data.Title);
self.Text = ko.observable(data.Text);
self.TextTags = ko.observableArray();
function createTypeComputed(tagType) {
return ko.computed(function () {
return ko.utils.arrayFilter(self.TextTags(), function (item) {
return item.Type() == tagType;
});
});
}
self.ManagerTags = createTypeComputed(0);
self.EmployeeTags = createTypeComputed(1);
self.LocationTags = createTypeComputed(2);
self.removeTag = function (tagToRemove) {
self.TextTags.remove(function (item) {
return item.Id == tagToRemove.Id;
});
}
}
标签对象如下所示:
var Tag = function(data){
var self = this;
self.Id = data.Id;
self.Name = ko.observable(data.Name);
self.Type = ko.observable(data.Type);
self.ParentTextId = data.TextId;
}
我希望数组“TestTags()”用过滤后的数组自动更新(也许是计算函数?)。 IE。 “ManagerTags()”(以及“EmployeeTags()”和“LocationTags()”)与“TextTags()”是双向绑定的,而不仅仅是上面代码所示的单向绑定。
见小提琴:http://jsfiddle.net/mnnEe/
示例:我希望“Textbatch.ManagerTags()”成为“Textbatch.TextTags()”的计算子集,其中 TagType=0。 但我想通过 select2-plugin 编辑和添加标签:
<input data-bind="value: ManagerTags, select2: {tags: ManagerTags, tokenSeparators: [',', ' ']}"/>
如果没有这种明显的循环引用,我如何实现这种 2-way 绑定?
【问题讨论】:
-
Select2 和 Knockout 可以很好地协同工作,如下所示 - github.com/ivaynberg/select2/wiki/Knockout.js-Integration - 您在此之外尝试做什么或为什么不清楚。
-
我已经编辑了文本。现在清楚了吗?
标签: javascript jquery knockout.js jquery-select2