passing data from methods in javascript
Totally new to OOP in javascript, but Im trying and reading all I can.
Ive created a simple test javascript class called Invoices. Invoices only has two methods. One method fires the other. And this part seems to be working fine.
My problem lies with getting data objects from one method to another. I put a alert in the first method, (from my understanding) this alert should show data returned from the second method... but its not.
Any help would be greatly appreciated. Oh.. and I am using jquery as well.
Here is my codez.
function Invoices()
{
this.siteURL = "http://example.com/";
this.controllerURL = "http://example.com/invoices/";
this.invoiceID = $('input[name="invoiceId"]').val();
}
invoice = new Invoices;
Invoices.prototype.initAdd = function()
{
开发者_运维问答 //load customers json obj
this.customersJSON = invoice.loadCustomers();
alert(this.customersJSON);
//create dropdown
}
Invoices.prototype.loadCustomers = function ()
{
$.post(this.controllerURL + "load_customers"),
function(data)
{
return data;
}
}
There are two problems with that. First of all, $.post
is asynchronous; you'll have to adopt a callback scheme or use $.ajax
to make it synchronous. Secondly, you probably meant to do this:
$.post(this.controllerURL + "load_customers", function(data) {
return data;
});
Note how the closure is in the parentheses of the function call.
As you were told the AJAX call is asynchronous, you would have to implement your initAdd in 2 step:
BeginInitAdd
which would initiate the AJAX callEndInitAdd
which would be the callback for your AJAX call and perform the action depending on the data returned.
Invoices.prototype.initAdd = function()
{
//load customers json obj
this.xhrObj = invoice.loadCustomers();
alert(this.customersJSON);
}
Invoices.prototype.createDropdown = function (data) {
//create dropdown
this.customersJSON=data
}
Invoices.prototype.loadCustomers = function ()
{
return $.post(this.controllerURL + "load_customers"),
function(data)
{
//return data;
this.createDropdown(data)
}
}
精彩评论