如何预选Section in knockout-postbox.js让内容可见

How to preselect Section in knockout-postbox.js so that the content is visible

在深入了解 Ryan Niemeyer 的辉煌之后 knockout-postbox.js 我做了一些小调整,希望菜单以预选部分打开。因此,我在 selectedSection 可观察对象的初始化中添加了一个变量,如下所示。

var MenuModel = function() {

    var preselected = "Profile";
    this.name = ko.observable().subscribeTo("nickName");
    this.sections = ["Profile", "Notifications","Users","Projects"];
    this.selectedSection = ko.observable(preselected).publishOn("section");
};

这会选择所需的部分,但该部分的内容仍然不可见。

这是预选的部分 viewModel:

var ProfileModel = function() {
    //apply a filter to turn the value that we receive into a boolean
    this.visible = ko.observable().subscribeTo("section", function(newValue) {
        return newValue === "Profile";
    });

   //some more code - syncing and subscribing/publishing observables.
};

HTML 是这样的:

<div id="menu">
    <h2><span data-bind="text: name"></span>'s Settings</h2>
    <ul class="nav nav-pills" data-bind="foreach: sections">
        <li data-bind="css: { active: $root.selectedSection() === $data }">
            <a href="#self" data-bind="text: $data, click: $root.selectedSection"></a>
        </li>
    </ul>
</div>


<div id="profile" data-bind="visible: visible">
    <h3>Profile</h3>
    <label>Nick name: <input id="nick" data-bind="value: nickName" /> </label>
    <label>Email: <input data-bind="value: emailAddress" /></label>
</div>

问题是,如何使用 MenuModelselectedSection 可观察对象的预选设置来触发 ProfileModelvisible 可观察对象,以便内容显示了吗?

完整 fiddle: http://jsfiddle.net/AsleG/b6gwn6ak/

subscribeTo 助手可以将布尔值作为第二个参数,以指示您要使用上次发布的值对其进行初始化。然后可以将您的比较函数作为第三个参数传递。它看起来像:

//apply a filter to turn the value that we receive into a boolean
this.visible = ko.observable().subscribeTo("section", true, function(newValue) {
    return newValue === "Profile";
});