I am trying to make some of my javascript a bit more testable, as part of this I am wrapping up certain functionality in classes so I can mock it out in my tests.
Anyway I am trying to wrap up my ajax, so as far as my app would be concerned it is asking a service for an object. Internally it would make an ajax request and then do something with the data and then return it.
So would something like the example below be possible? (I am on the move at the moment so cant try it for myself)
function SomeAjaxService(webServiceUrl)
{
this.getSomeModel = function(someUniqueId){
var ajaxOptions = {
url: webServiceUrl,
data: {id : someUniqueId},
Success: function(data) { return new SomeModel(data); }
};
$.ajax(ajaxOptions);
};
}
var ajaxService = new SomeAjaxService("http://someurl");
var myModel = ajaxService.getSomeModel(1);
As ajax is asynchronous by nature, I think you can set it to be synchronous but I just wanted to check what the options were…
Setting it to synchronous is a bad idea as you will lock javascript (even the browser) until the request returns. Your code will not work because the success function is called from a different context to your direct
getSomeModelmethod call. The best approach would be for you to callgetSomeModeland pass it a callback function that will be executed when the model is received.