Friday, 15 March 2013

jquery - KnockoutJS UI not binding on first load -



jquery - KnockoutJS UI not binding on first load -

this first stab @ knockoutjs. code below. getjson phone call working. can see response in fiddler , have validated jslint (ie json response). can see array beingness populated in chrome console, reason ui not updating info fetch server. can see i've missed?

<script type="text/javascript"> function section(data) { this.id = ko.observable(data.id); this.name = ko.observable(data.name); this.selected = ko.observable(data.selected); } function sectionsviewmodel() { var self = this; self.viewname = ko.observable(); self.sections = ko.observablearray([]); // initial load $.getjson("/service/view/getjson?viewid=@viewbag.viewid", function (alldata) { self.viewname = alldata.viewname; var mappedsections = $.map(alldata.sections, function (item) { homecoming new section(item) }); self.sections = mappedsections; }); } ko.applybindings(new sectionsviewmodel()); </script> <h2>edit view</h2> <table class="dataentrytable"> <thead> <tr> <th>id</th> <th>name</th> <th>selected</th> </tr> </thead> <tbody data-bind="foreach: sections"> <tr> <td data-bind="text: id()"></td> <td data-bind="text: name()"></td> <td><input type="checkbox" data-bind="checked: selected()" /></td> </tr> </tbody> </table>

update ko observables function:

self.viewname(alldata.viewname); var mappedsections = $.map(alldata.sections, function (item) { homecoming new section(item) }); self.sections(mappedsections);

also in binding, remove parenthesis (you binding value of observable instead of observable itself):

<td data-bind="text: id"></td> <td data-bind="text: name"></td> <td><input type="checkbox" data-bind="checked: selected" /></td>

finally, need phone call ko.applybindings(new sectionsviewmodel()); after html has rendered bind loaded html view model (either set script after html, or utilize event phone call on document ready).

jquery knockout.js

No comments:

Post a Comment