I am using MVC 4.0 with knockout.js to create a page that will invoke the database every 5-10 seconds and update the model with a new object retrieved from the database and then update the view with the new model.
I am currently making the initial JSON call, and this returns a model, and then I can associate this with the view. Then I set up the getJSON call again to do the update every 10 seconds, and it will execute this function and return the data, but the update will not appear on the screen. I tried calling ko.applyBindings after each call, but there is still no refresh on the page, after which it is called from the browser after several calls.
I'm not sure what exactly I am doing wrong. I have included the relevant parts of the code below.
JavaScript:
<script type="text/javascript"> var viewModel; var update = setInterval(function () { $.getJSON( "/Home/Get", {}, function (model) { viewModel = model; bindViewModel(viewModel); }); }, 10000); $(document).ready( function () { $.getJSON( "/Home/Get", {}, function (model) { viewModel = model; bindViewModel(viewModel); }); }); function bindViewModel(viewModel) { ko.applyBindings(viewModel); } </script>
Table for displaying the model
<div data-bind="foreach: { data: Events, as: 'evnts' }"> <span data-bind="text: evnts.LastUpdate"></span> <table id="EventsTable" style="display:inline; float:left;"> <tbody> <tr id="EvntsHeader" data-bind="visible: evnts.IsVisible"> <td> <span data-bind="text: evnts.Name"></span> </td> <tr> <td> <table id="MarketsTable"> <tbody data-bind="foreach: { data: evnts.Markets, as: 'markets' }"> <tr> <td id="MarketHeader"> <span data-bind="text: markets.Name"></span> <span data-bind="text: markets.NumberOfRunners"></span> </td> </tr> <tr> <td> <table id="SelectionTable"> <tbody data-bind="foreach: { data: markets.Selections, as: 'selections' }"> <tr id="Selections"> <td><span data-bind="text: selections.Number, visible: selections.IsVisible"></span></td> <td><span data-bind="text: selections.Name, visible: selections.IsVisible"></span></td> <td><span data-bind="text: selections.CurrentPrice, visible: selections.IsVisible"></span></td> <td><span data-bind="text: selections.OpeningPrice, visible: selections.IsVisible"></span></td> </tr> </tbody> </table> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table>
Controlller - JSON Get
[AcceptVerbs(HttpVerbs.Get)] public JsonResult Get() { var model = new TestModel {LastUpdate = DateTime.Now}; if (TestConstants.Update == false) { GetModelFirstTime(model); TestConstants.Update = true; } else { UpdateModel(model, DateTime.Now); } return Json(model, JsonRequestBehavior.AllowGet); }