简体   繁体   English

淘汰赛添加计算的中断可观察数组

[英]Knockout adding computed breaks observable array

Hi I am trying to use a computed value to make a filtered version of an observable array as per the example here http://knockoutjs.com/documentation/fn.html ( right at the bottom). 嗨,我正在尝试使用计算值来制作可观察到的数组的过滤版本,如此处http://knockoutjs.com/documentation/fn.html上的示例所示(位于底部)。

For the html I have have 对于HTML我有

<select  width="50px" data-bind="options: $root.resources, optionsText: 'Name'"></select>
<select  width="50px" data-bind="options: $root.available, optionsText: 'Name'"></select>​

And my viewModel looks like this: 我的viewModel看起来像这样:

var viewModel = function() {
    var self = this;
    self.resources = ko.observableArray([{Name: "Anna",Available: true}, {Name: "Bert", Available: false}]);  

    self.getFilteredResources = function (isAvailable) {
        var all = self.resources(), results = [];
        var resource;
        for (resource in all){
            if (resource.Available() === isAvailable){
                results.push(resource);
            }
        }
        return results;
    };    
    //self.available = ko.computed(function() { self.getFilteredResources( true);}, this);    
};

ko.applyBindings(new viewModel());​

You can also see the code here http://jsfiddle.net/patrickhastings/eCtFY/1/ 您也可以在此处查看代码http://jsfiddle.net/patrickhastings/eCtFY/1/

As it stands the out put is one dropdown with Anna and Bert in it and one empty which is fine. 就目前而言,结果是一个下拉列表,其中包含Anna和Bert,另一个为空,这很好。

When I uncomment out the line to declare self.available instead of the second dropdown being populated with Anna, I get two empty drop downs. 当我取消注释该行以声明self.available而不是用Anna填充第二个下拉列表时,我得到两个空的下拉列表。 Help Please tell me where I am being dumb. 帮助请告诉我我在哪里傻。

A couple small issues in this one: 这个问题有两个小问题:

You are calling resource.Available() and Available is not an observable, so you just need to check resource.Available === isAvailable . 您正在调用resource.Available()Available并不是可观察的,因此您只需要检查resource.Available === isAvailable

Additionally, your computed observable needs to return the result of self.getFilteredResources 此外,您计算出的可观察值需要return self.getFilteredResources的结果

Doing for resource in all will give you the index rather than the resource itself. for resource in all将为您提供索引,而不是资源本身。

I would recommend something like: http://jsfiddle.net/rniemeyer/jCYT7/ 我会推荐类似的东西: http : //jsfiddle.net/rniemeyer/jCYT7/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM