当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - knockoutjs change view with bindig

问题描述:

I want to show and hide selected views with knockout js api. My view models are like this.

var profileModel = {

first: ko.observable("First name"),

last: ko.observable("Last name"),

};

var settingsModel = {

isActive: ko.observable(true)

};

var notificationsModel = {

emailAddress: ko.observable("[email protected]")

};

And I have a shell viewmodel to manage sub viewmodels:

var shellModel = {

sections: ["profile", "settings", "notifications"],

selectedSection: ko.observable(),

}

ko.applyBindings(shellModel);

My navigation view looks like this:

<ul data-bind="foreach: sections">

<li>

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

</li>

</ul>

When a user clicks this link, the selected view should appear, and the others should not appear.

Profile view is like this.

<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>

网友答案:

create close function in every view model, on click of this it will show default or home view and hide the current view.

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

close button binding:-

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

Then default view:-

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

Fiddle Demo

网友答案:

Have you tried this:

<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>

and your 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("[email protected]") 
  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);

Just guessing, a easy fiddle would be nice.

分享给朋友:
您可能感兴趣的文章:
随机阅读: