javascript - AJAX-ed webpage. How do I bring initial data? -
i have webpage tabular data. right uses knockout.js bindings.
when page loads make ajax call bring data , bind. basically, page displayed first , user gets "loading..." ajax message , data comes. nice because page loads fast browser has make 2 calls server (one page , data).
if user want refresh data - works nicely same way.
i know how load viewmodel data page? way can avoid double-trip server? i'd somehow include json on initial page load , work , refresh using ajax.
edit:
i got working, not sure if there gotchas way did it:
html:
<div id="initialdata" style="display: none;"><asp:literal id="initialdataliteral" runat="server" enableviewstate="false"/></div>
server code:
// prepare initial data page var memorystream = new memorystream(); var serializer = new datacontractjsonserializer(typeof(dataenvelope)); serializer.writeobject(memorystream, getshipments(datetime.now.date.addmonths(-2).toshortdatestring(), datetime.now.date.toshortdatestring())); memorystream.position = 0; var streamreader = new streamreader(memorystream); this.initialdataliteral.text = streamreader.readtoend();
on knockout side it's easy, take string out, convert json , go it..
// page comes preloaded data. let's set vm properties var initialdata = $.parsejson($("#initialdata").text()); vm.tripdata(ko.utils.arraymap(initialdata.shipments, function (i) { return new shipment(i); }));
later when user hit's refresh same data via ajax call. there drawbacks having this? view source gives bunch of json "stuff". still think page more compact , first load faster comparing fully-ajaxed loading..
you didn't specify server-side technology you're using, did @ least tag question asp.net
. pattern use asp.net mvc, if you're using web forms may have adjust it.
var modeldata = @html.raw(json.encode(model)); var myviewmodel = function (data) { var model = ko.mapping.fromjs(data); // additional observables, computeds, methods, etc., i.e. // model.somethingnotonmodel = ko.computed(); return model; }; var viewmodel = myviewmodel(modeldata); ko.applybindings(viewmodel);
knockout's mapping plugin automatically create observables whatever properties exist on data object fed it, don't need specify manually, unless need change them.
update
based on @rich's comment, felt should display little more how should use this:
in page
<script> $(document).ready(function () { var modeldata = @html.raw(json.encode(model)); myapp.myview.init(modeldata); }); </script>
external js
myapp = myapp || {}; myapp.myview = function () { var _init = function (data) { var viewmodel = myapp.myview.myviewmodel(data); ko.applybindings(viewmodel); // else should happen on page load }; return { init: _init }; }(); myapp.myview.myviewmodel = function (data) { var model = ko.mapping.fromjs(data); // additional observables, computeds, methods, etc., i.e. // model.somethingnotonmodel = ko.computed(); return model; };
Comments
Post a Comment