Knockoutjs中的子视图模型

时间:2015-05-07 11:39:35

标签: javascript knockout.js

很满意!

我正在玩Knockoutjs,其目标是拥有一个控制多个子视图模型的ViewModel。这样可以更好地控制视图本身,并防止将视图的各个部分放入自己的小地方。下面的代码应该解释我的想法:

ApplicationViewModel

ApplicationViewModel = function () {
var self = this;

// Context (for laziness' sake, no separate VM)
self.activeProject = ko.observable();

// States
self.projectsLoaded = ko.observable(false);

// State-change events
// Let application know that loading of projects has been called
self.projectsLoaded.subscribe(function (newValue) {
    if (newValue === true) {
        console.log('Projects have loaded');
    } else {
        console.log('Projects have not loaded');
    }
});
// Let application know that selection of a project has happened
self.activeProject.subscribe(function (newValue) {
    if (newValue != null) {
        // Notify other viewmodels that a project has been (successfully loaded)
        // Use hook-pattern to hook into this event
    } else {
        // Notify something went wrong- present user with a notification
        // Application stops processes that are project-dependant
    }
});

self.ProjectViewModel = new ProjectViewModel();
};

ProjectViewModel

ProjectViewModel = function () {
var self = this;

self.projects = ko.observableArray();

self.loadProjects = function () {
    // Business logic to retrieve projects, think AJAX
    var placeHolderProjects = [];

    // Find projects somewhere and load them up!

    // If something went wrong, notify parent
    if (placeHolderProjects.length > 0) {
        self.projects(placeHolderProjects);
        $root.projectsLoaded(true);
    } else {
        $root.projectsLoaded(false);
    }
};

self.selectProject = function (projectId) {
    if (!projectId) {
        $.parent.activeProject = null;
        return;
    }

    // Fetch data for project, stuff like membershipId
    var loadProjectResult = magicalLoadFunction(projectId);

    if (loadProjectsResult === true) {
        $root.activeProject(projectId);
    } else {
        $root.activeProject(projectId);
    }

    // Exit
    return;
}

/********** Constructor logic
****************************/
self.loadProjects();
};

基本上,我正在寻找的是一种方法: - 控制来自各自子/父里面的视图模型的父/子属性。

我也在研究AngularJS,但我真的很想在KnockoutJS中首先使用它:)直接的问题是,我无法让$ root / $ parent工作。我将ApplicationViewModel绑定在$(document).ready()处理程序中,不确定是否必须将子视图模型实际绑定到视图中。我已将ApplicationViewModel绑定到body元素。

感谢阅读,并可能回答/帮助我继续前进:)

1 个答案:

答案 0 :(得分:0)

@ jansommer提供的答案证明是成功的。

我更改了以下行(将其添加为参数):

self.ProjectViewModel = new ProjectViewModel(this);

这就是所需要的。

谢谢!