【问题标题】:How to create a Two-way ko.computed() array filter如何创建双向 ko.computed() 数组过滤器
【发布时间】: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 绑定?

【问题讨论】:

标签: javascript jquery knockout.js jquery-select2


【解决方案1】:

我很难弄清楚你到底想要做什么。但我想我有一个想法。我唯一可以建议的是您的 Textbatch 对象具有所选过滤器的 observable。然后订阅那个 observable。即将它添加到您的 Textbatch 对象中。

self.selectedFilter = ko.observable(/*optionally set a default*/);
self.selectedFilter.subscribe(function(newValue){
switch(newValue){
    case 0:
    //Do your stuff
    break;
    case 1:
    //Do your stuff
    break;
    case 2:
    //Do your stuff
    break;
    default:
    break;
}
});

现在,当您制作并更改为 Textbatch.selectedFilter 时,您可以通过 switch 语句更新整个对象。

【讨论】:

    猜你喜欢
    • 2013-03-30
    • 1970-01-01
    • 2018-11-28
    • 2023-03-19
    • 1970-01-01
    • 2015-03-29
    • 1970-01-01
    • 1970-01-01
    • 2018-05-08
    相关资源
    最近更新 更多