javascript - how to do data-bind for complex model knockout -
i newbee knockout, i'm trying move mvc viewmodel binding.
i have complex model:
searchstudentsmodel has 2 properties
- collection of students (subset of students)
- number of students overall
note length of collection isn't equal number overall.
i need implement search functionality student have regular properties plus isactive indicator. use ul , li tags data-bind details.
the search screen should facilitate user in marking active flag indicator (on , off) , data should saved in database.
all examples referred talk 1 level of model. have searchstudent model , within have collection of students.
how should binding hierarchy of models?
i have refactored jsfiddle. hoping can understand knockoutjs better. not whole page/knockout, think snippet problem can solved.
the markup:
<button id="searchemployees" type="button" data-bind="click: search">search</button> <li data-bind="foreach: employees"> id: <span data-bind="text: id"></span><br/> name: <span data-bind="text: name"></span><br/> active: <span data-bind="click: toggleactivation, text: isactive"></span> <-- click<br/> </li> <span data-bind="text: employees().length"></span> of <span data-bind="text: allemployees().length"></span>
the js/viewmodel
function employee(id, name, isactive){ var self = this; self.isactive = ko.observable(isactive); self.id = ko.observable(id); self.name = ko.observable(name); self.toggleactivation = function () { if(self.isactive() === true) self.isactive(false); else self.isactive(true); }; } var searchemployeeviewmodel = function () { var self = this; self.employees = ko.observablearray([]); self.allemployees = ko.observablearray([]); self.search = function () { //ajax call populate employees - foreach on onsuccess var employee1 = new employee(2, "jane doe", true); var employee2 = new employee(3, "kyle doe", false); var employee3 = new employee(4, "tyra doe", false); var employee = new employee(1, "john doe", true); self.allemployees.push(employee); self.allemployees.push(employee1); self.allemployees.push(employee2); self.allemployees.push(employee3); self.employees.push(employee); } } $(document).ready(function () { ko.applybindings(new searchemployeeviewmodel()); });
or can simply use my jsfiddle if not reading code here ;)
Comments
Post a Comment