简体   繁体   English

如何从不同的对象范围访问挖空可观察对象

[英]How to access knockout observables from different object scopes

My data model is consisting of two objects; 我的数据模型由两个对象组成; project and task. 项目和任务。 I load my data from the db via json and MVC-services and map my observableArrays like this: 我通过json和MVC服务从数据库加载数据,并映射我的observableArrays,如下所示:

viewModel = function () {
    var self = this;

    // some code...

    // projects
    self.Projects = ko.observableArray();
    var mappedProjects = [];
    $.ajax({
        url: "myService/GetProjectsByUserId",
        data: "userID=" + meID,
        dataType: 'json',
        async: false,
        success: function (allData) {
            mappedProjects = $.map(allData, function (item) {
                return new Project(item);
            });
        }
    });
    self.Projects(mappedProjects);

    // tasks
    self.Tasks = ko.observableArray();
    var mappedTasks = [];
    $.ajax({
        url: "myService/GetTasksByUserID",
        data: "userid=" + meID,
        dataType: 'json',
        async: false,
        success: function (allData) {
            mappedTasks = $.map(allData, function (item) {
                return new Task(item, self.Projects);    // is there a smarter way to access self.Projects from the Scene prototype?
                //return new Task(item);
            });
        }
    });
    self.Tasks(mappedTasks);


    //some more code...

};

where 哪里

Project = function (data) {
    this.projectID = data.projectID;
    this.type = ko.observable(data.type);
};


Task = function (data, projects) {

    this.taskID = data.taskID;
    this.projectID = data.projectID;

    //this.projecttype = ??? simpler solution?

    this.projecttype = ko.computed(function () {   // Is there a simpler way to access 'viewModel.Projects' from within 'Task'?
        var project = ko.utils.arrayFirst(projects, function (p) {
            return p.projectID === self.projectID;
        });
        if (!project) {
            return null;
        }
        else {
            return project.headerType();
        }
    });

};

The thing is (as you see) I want to access the projectType inside the Task-object. 事情是(如您所见),我想访问Task-object内的projectType。 Is there a simpler way to do this than instantiating the object with the self.Projects as input? 有没有比使用self.Projects作为输入实例化对象更简单的方法呢?

Could self.Projects be bound when defined in some way so I could access it via the DOM? 可以通过某种方式绑定self.Projects以便我可以通过DOM访问它吗?

From your comments, it looks like that you have multiple view models dependent on Task and Project objects. 从您的评论看来,您具有依赖于TaskProject对象的多个视图模型。 For decoupling between components, i would say to use ko.postbox plugin. 对于组件之间的解耦,我会说使用ko.postbox插件。 You can easily have synchronization between viewmodels and non-knockout components using publishOn and subscribeTo extensions. 您可以轻松地在使用的ViewModels和非淘汰赛组件之间的同步publishOnsubscribeTo扩展。

So your Task object will subscribe to Projects observableArray in viewModel like 因此,您的Task对象将在viewModel中订阅Projects observableArray ,例如

Task = function (data) {

    this.taskID = data.taskID;
    this.projectID = data.projectID;
    var projects = ko.observableArray().subscribeTo("projectsLoaded",true);

    //this.projecttype = ??? simpler solution?

    this.projecttype = ko.computed(function () {   // Is there a simpler way to access 'viewModel.Projects' from within 'Task'?
        var project = ko.utils.arrayFirst(projects(), function (p) {
            return p.projectID === self.projectID;
        });
        if (!project) {
            return null;
        }
        else {
            return project.headerType();
        }
    });

};

and in your viewModel, you just have to make Projects observable array publish "projectsLoaded" topic/event. 并且在viewModel中,您只需要使Projects可观察的数组发布“ projectsLoaded”主题/事件即可。 Like 喜欢

viewModel = function () {
    var self = this;
    // some code...
    // projects
    self.Projects = ko.observableArray().publishOn("projectsLoaded");
    // ....
}

Whenever the projects array changes in viewModel, you will always have the latest value in Task project array. 每当viewModel中的projects数组发生更改时,您在Task project数组中将始终具有最新值。

JsFiddle: http://jsfiddle.net/newuserjs/wffug341/3/ JsFiddle: http : //jsfiddle.net/newuserjs/wffug341/3/

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

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