knockoutjs用bindig改变视图

时间:2014-03-17 13:00:41

标签: javascript jquery knockout.js

我想用knockout js api显示和隐藏所选视图。我的观点模型是这样的。

var profileModel = {
    first: ko.observable("First name"),
    last: ko.observable("Last name"),
};

var settingsModel = {
    isActive: ko.observable(true)        
};

var notificationsModel = {
    emailAddress: ko.observable("sample@mail.net")  
};

我有一个shell viewmodel来管理子 viewmodels

var shellModel = {
    sections: ["profile", "settings", "notifications"],
    selectedSection: ko.observable(),   
}
ko.applyBindings(shellModel);

我的导航视图如下所示:

<ul data-bind="foreach: sections">
   <li>
        <a href="#" data-bind="click: $root.selectedSection, text: $data"></a>
   </li>
</ul>

当用户点击此链接时,应显示所选视图,而不应显示其他视图。

个人资料视图就是这样。

<div data-bind="with: ???">
    <div id="profile">
        <input data-bind="value: first" />
        <input data-bind="value: last" />
    </div>
    <button data-bind:"click: ???">Close</button>
</div>

2 个答案:

答案 0 :(得分:1)

在每个视图模型中创建关闭函数,单击此按钮将显示默认或主视图并隐藏当前视图。

var profileModel = {
 first: ko.observable("Bob"),
 last: ko.observable("Smith"),
 closeit: function () {
    shellModel.selectedSection("default");
 }
};

关闭按钮绑定: -

 <input type="button" data-bind="click: closeit" value="close" />

然后是默认视图: -

<div data-bind="visible: selectedSection() === 'default'">
    <div id="default">
        <div>Home page</div>
    </div>
</div>

Fiddle Demo

答案 1 :(得分:0)

你试过这个:

<ul data-bind="foreach: sections">
   <li>
        <a href="#" data-bind="click: $root.sectionChangedClick, text: name"></a>
   </li>
</ul>
<div data-bind="with: selectedSection">
    <div id="profile">
        <input data-bind="value: first" />
        <input data-bind="value: last" />
    </div>
    <button data-bind:"click: clickClose">Close</button>
</div>

和您的ViewModel:

var profileModel = {
   first: ko.observable("First name"),
   last: ko.observable("Last name"),
   name: "profile"
 };

var settingsModel = {
  isActive: ko.observable(true),
  name: "settings"
};

var notificationsModel = {
  emailAddress: ko.observable("sample@mail.net") 
  name:"notifications" 
};

var shellModel = {
    sections: ko.observableArray([profileModel, settingsModel, notificationsModel]),
    selectedSection: ko.observable(), 
    clickClose: function() {
        this.selectedSection(null);
    },
    sectionChangedClick: function(section) {
        this.selectedSection(section);
    }  
}
ko.applyBindings(shellModel);

只是猜测,一个简单的小提琴会很好。