Reputation: 329
I am trying a MVC sample that pulls the data from DB, and shows inside a table (using Knockout JS). I want to apply dark-stripe and light-stripe to rows. Stripes shows up only when I apply the CSS, right after calling ko.applyBindings(viewModel), not any where else.
Please help me understand what is going on here. Seems like a fundamental stuff, related to rendering of HTML.
Pseudo code
Ajax_call()
{
Fetch data from MVC controller(Web API)
Call knockout to construct table
Apply stripes. Stripes appear and stay.
}
NavigateToNextPage()
{
Call strip() from here, stripes appear JUST momentarily.
It is so fast that I can see it ONLY when I put a break-point inside
controller. It seems when Knockout draws the NEXT page, it removes
stripes.
Ajax_call();
Same problem if I call from here.
}
Full code
abc.js
=======
function getData()
{
$.ajax(
{
type: "get",
url: "/api/CollaborationSpaces/Page/" + CurrentPage,
cache: false,
context: this,
dataType: "json",
success: function (data)
{
var viewModel = ko.mapping.fromJS(data);
ko.applyBindings(viewModel);
//**IMPORTANT** If I call stripe() from here, I see stripes.
}
});
}
var CurrentPage = 1
function stripe()
{
$("tr:even").addClass("even");
$("tr:odd").addClass("odd");
}
function Move(pages)
{
CurrentPage = CurrentPage + pages;
//**IMPORTANT**
//If I call strip() from here, stripes appear momentarily.
//It is so fast, I can see it ONLY when I put break-point inside
//controller. It seems when Knockout draws the NEXT page, it removes
//stripes
getData();
//IMPORTANT this stripe has no effect.
stripe();
}
CSS
===
.odd {
background-color: #ebeced;
}
.even {
background-color: #99acb9;
}
Razor
=====
<h2>@ViewBag.Title</h2>
<p><span id="ItemsFound" data-bind="text: NumberOfResults"></span> Records Found</p>
<p>Page <span id="PageNumber" data-bind="text: CurrentPage"></span></p>
<br />
<table data-bind="template: {name: 'CollaborationSpaceTemplate', foreach:PersonInfoResults}" class="grid">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tfoot>
<tr>
<td colspan=2 class="Pager">
<span id="back" onclick="Move(-1)">< Back</span>
<span id="next" onclick="Move(1)">Next ></span>
</td>
</tr>
</tfoot>
</table>
<div id="LoadingDiv">Loading. . .</div>
<script id="CollaborationSpaceTemplate" type="text/html">
<tr>
<td data-bind="text: FirstName"></td>
<td data-bind="text: LastName"></td>
</tr>
</script>
Upvotes: 0
Views: 38
Reputation: 16675
success: function (data) {
var viewModel = ko.mapping.fromJS(data);
ko.applyBindings(viewModel);
//**IMPORTANT** If I call stripe() from here, I see stripes.
}
Yes, you should call stripe()
from your callback (after applyBindings
) so that the elements you are trying to add classes to are present in the markup.
Upvotes: 1