You've written your click event handler right into your data-bind statement. That is, you've written *logic* in your *html*. It's considered a best-practice to keep all your logic in your code (js, view models, or support libraries), your structure in your HTML, and your style in your CSS. When they mix, things start getting more difficult, which is what you're running in to here. In the case of the code you posted, you've got a couple options to get that function out of your data-bind declaration:
*****Option One*******
Create a click handler for each menu item as a function of your view model. For example:
var viewModel = {
showEmployees : function(){ setModule('EmployeesTemplate',employeesVM); },
showDepartments : function(){ setModule('DepartmentsTemplate',employeesVM); },
...
}
and then your binding becomes simply:
<a href="#" data-bind="click:showEmployees">Employees</a>
<a href="#" data-bind="click:showDepartments">Departments</a>
This is the most straightforward way to get the click handlers out of the binding declaration, but we can go a step farther.
******Option Two*******
Turn the menu itself into an observable array and display it with knockout.
When knockout calls a click handler, it supplies the data item as the first parameter and the DOM event object as the second parameter. This allows you to handle all menu clicks with the same click handler, which continues to optimize your code against the DRY principal (Don't Repeat Yourself).
var viewModel = {
....
menu : new ko.observableArray([
{name: 'Employees', template : 'EmployeesTemplate'},
{name: 'Departments', template : 'DepartmentsTemplate'}
]),
menuItemClicked : function(dataItem, event){
var name = dataItem.name;
var template = dataItem.template;
setModule(template, this.employeesVM);
},
....
}
and then bind the menu with a foreach
<div id="subhead">
<span id="header">Master/Detail with nested viewmodels</span><br/>
<!-- ko foreach: menu -->
<a href="#" data-bind="click:$parent.menuItemClicked, text:name"></a> |
<!-- /ko -->
<hr/>
</div>
*****Clearing the View******
So, back to your original question; how do you reset the state of your view when a link is clicked? Well, now that your click handlers are easily accessable, it's a snap. Let's say you went with option two above. All you need to do is create a function that resets your view state and call it somewhere from within your click handler.
var viewModel = {
...
resetState : function(){
this.myModule({});
this.employeesVM.selectedEmployee(),//clear selected employee
this.employeesVM.selectedDepartment(),//clear selected department
this.employeesVM.searchTerm(),
this.employeesVM.setDepartment(),
this.employeesVM.getEmployees(),
this.employeesVM.getEmpDetails()
//whatever else needs to be reset to blank
},
menuItemClicked: function(dataItem, event){
this.resetState();
...//the rest from above
},
...
}
I hope this helps!
-Ryan Rahlf
______________________________
Sign up for my newsletter for more tips and tricks