I’m trying to make a simple grid system with knockout for my project. But I can not update the my viewmodel properly
here is my JS;
$(function () {
function AppViewModel(initialData) {
var self = this;
self.prices = ko.observableArray(initialData.Data);
self.TotalCount = ko.observable(initialData.TotalCount);
self.Page = new PageViewModel(initialData);
self.GoTo = function (d) {
$.getJSON("/prices/GetByFilterViaJSON?limit=3&page=" + d, function (data) {
self.Page = new PageViewModel(data);
self.prices(data.Data);
});
};
};
function PageViewModel(listData) {
var self = this;
ko.mapping.fromJS(listData.Page, {}, self);
}
$.getJSON("/prices/GetByFilterViaJSON?limit=3", function (data) {
ko.applyBindings(new AppViewModel(data));
});
});
and HTML
<div class="section table_section">
<div class="section_inner">
<div class="title_wrapper">
<h2 data-bind="text: TotalCount">
Prices</h2>
</div>
<div class="section_content">
<div id="product_list">
<div class="table_wrapper">
<div class="table_wrapper_inner">
<table cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<th>
No.
</th>
<th>
Tier
</th>
<th>
</th>
</tr>
<!-- ko foreach: prices -->
<tr data-bind="css:{first: $index % 2 == 0}">
<td data-bind="text: Id" style="width: 26px;">
</td>
<td data-bind="text: Tier" style="width: 35px;">
</td>
<td style="width: 120px;">
<div class="actions_menu">
<ul>
<li><a class="edit" href="">edit</a></li>
<li><a class="delete" href="">deny</a></li>
</ul>
</div>
</td>
</tr>
<!-- /ko -->
</tbody>
</table>
</div>
</div>
</div><!-- PAGING NUMBERS -->
<div class="pagination"><!-- HERE NOT UPDATING -->
<span class="page_no" data-bind="text: Page.CurrentPage()"></span>
<ul class="pag_list" data-bind="foreach: ko.utils.range(1, Page.TotalPage)"> <!-- AND HERE NOT UPDATING -->
<li><a href="" data-bind="click: $root.GoTo, css:{current_page: $data==$root.Page.CurrentPage()}"><span><span data-bind="text: $data"></span></span></a>
</li>
</ul>
</div>
</div>
</div>
When I click to paging numbers (GoTo function in viewModel), self.Page is not updated thus page number class is always same. That is What I can’t success.
You think what am I doing wrong?
Knockout does not know about your new PageViewModel when you do this in your
GoTomethod:The UI is bound against the previous PageViewModel and does not know about this new one. You would likely want to make
self.Pagean observable and populate it with the current PageViewModel. So, then yourGoTomethod would do:You would initially define it like:
In your UI, you would then need to either do
with: Pagearound your section or access the values likePage().CurrentPage.