Confused about a stupid Javascript thing
-
So, I'm using Pager.js to deal with a single-page-app. So far, it's been really straight-forward, but the documentation started using modules I've never used (require.js) to do code injection. Normally, I'd use jQuery to handle code injection (by hitting the server for some JSON, instead of loading a static module).
Can anybody help? I'm trying to translate:
# the model, I think, under a bunch of layers define(function () { return { getVM:function () { return { name:"What-if Machine", description:'Can show how the world would be if something was.' }; } }; }); # the lazy loader var requireVM = function (module) { return function (callback) { require([module], function (mod) { callback(mod.getVM()); }); }; }; # the binding: <div class="well" data-bind="page: {id: 'invention', withOnShow: requireVM('invention')}">
into a jQuery version.
Since I'm not loading a module at all, I can get rid of the 'invention' argument right off the bat. But then, what do I replace the
require
with? I presumed to do something like:var requireVM = function () { return function (callback) { $.getJSON(myurl, function (result_data) { callback(????) } } }
-
return function (callback) {
$.getJSON(myurl, function (result_data) {
callaback(????)
}Without knowing javascript, or jquery, and just general rules of programming..
wouldn't it be callaback(callback)?
-
Let me reconstruct what I had. I scrapped it all in a fit of frust-rage-tion. It was doing something extremely stupid.
-
I think you're looking for getVM for callback(????)?
-
So the object that corresponds to the thing that holds
getVM
is defined by:var ViewModel = function (data) { var self = this; ko.mapping.fromJS(data, {}, self); self.getExamHistory = function () { return function (callback) { $.getJSON("@{ExamHistoryR}", function (data) { self.history = ko.mapping.fromJS(data, {}, self); callback(self.history); }); } } };
So that
getExamHistory
pretty much replaces/joinsrequireVM
. But when I try to run this and bind it in my view model, I don't get a viewModel.history. I also don't get named fields, since the history is an array. :-/ I have no idea how to inspect the value.
-
Are you sure
require
is an async operation? Maybe it expects it to be loaded before it all renders, but$.getJSON
is async by default IIRC.Also, on the front of inspecting arrays, if you just want to see what's in it you could always just
console.log
it for a quick and dirty test. Consoles in today's browsers are perfectly capable of displaying both arrays and objects.
-
I'm not sure. I'm looking into it. It sucks that the project is named 'require' and also the method is named 'require'.
Edit: yes, it's async by default.
-
I found an example on pager.js's api documentation page. Doing the thing now.