Knockout.Js数组过滤器语法 [英] Knockout.Js Array filter syntax

查看:143
本文介绍了Knockout.Js数组过滤器语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚进入javascript和knockout.js。我找到了一堆我想要完成的例子。我觉得我可能会忽略一个小的语法错误。我正在尝试通过ajax / json从服务器过滤已经返回的集合( this.tasks )。我工作得很好。我想做的是让用户能够在完成和不完整的任务之间切换。

Just getting into javascript and knockout.js. I've found a bunch of examples of what I'm trying to accomplish. And I feel like there is a small syntax error I may be overlooking. I'm trying to filter a set already returned (this.tasks) from a server via ajax/json. I have that working fine. What I would like to do, is have users be able to switch between complete and incomplete tasks.

我将代码切换到在tasksFiltered上运行foreach循环。 this.done是真还是假。

I switched the code to just run the foreach loop on tasksFiltered. "this.done" is either true or false.

任务模板

var taskModel = function(id, title, description, done){
    var self = this;
    this.id = ko.observable(id);
    this.title = ko.observable(title);
    this.description = ko.observable(description);
    this.done = ko.observable(done);

    this.showEdit = ko.observable(false);
    this.titleUpdate = ko.observable(false);
    this.descriptionUpdate = ko.observable(false);
};

页面模型

var pageModelTasks = function(){
    var self = this;
    this.task_title = ko.observable("");
    this.task_description = ko.observable("");
        this.task_title_focus = ko.observable(true);
    this.tasks = ko.observableArray([]);

    this.tasksFiltered = ko.computed(function() {
        return ko.utils.arrayFilter(this.tasks, function(Task) {
        return Task.done == true;
      });
    });

   // CRUD functions excluded 
}; 

这不起作用。

推荐答案

对您的代码进行两次小修改。首先,正如@XGreen所提到的,你需要传递数组值而不是 observableArray实例,作为 arrayFilter 函数的第一个参数。最后,因为 Task.done 是可观察的,所以需要调用该成员来获取值。这是修改后的代码:

Two minor corrections to your code. First, as @XGreen mentioned, you need to pass the array value, not the observableArray instance, as the first parameter of the arrayFilter function. Lastly, because Task.done is observable, you need to invoke the member to get the value. Here's the modified code:

this.tasksFiltered = ko.computed(function() {
    return ko.utils.arrayFilter(this.tasks(), function(Task) {
        return Task.done() === true;
    });
});

这篇关于Knockout.Js数组过滤器语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆