开发者

Using objects to correctly replace global variables

I've been trying to figure out how to initialize an object using a prototype in order to escape usi开发者_如何学Cng global variables, which I first learned about here. I began implementing my own version of the code found in the accepted answer.

function XML_Data() {
  this.data = null;
}

XML_Data.prototype = {
 GetXML: function() {
  $.ajax({
   type: "GET",
   url: "questions.xml",
   dataType: "xml",
   success: function(xml) {
    this.data=xml;
   } //close success
  });//close AJAX  
 },

 UseXML: function() {
  alert(this.data)
 }
};

(My implementation of the script)


However, I've run into a problem. When I run the functions shown here by using this bit of code:

var data = new XML_Data();
data.GetXML();
data.UseXML();

I get an alert that says "null". I've been through the code about a dozen times, but as this is my first time working with Javascript, there's quite obviously something I've missed. Could you point that out?

Thanks, Elliot Bonneville.


Just of note

var data = new XML_Data();
data.GetXML();  //This will run the ajax request
data.UseXML();  //This will most likely run before the ajax request is finished.

Publishing events in Jquery would problably work,but I havent tested this code.

function XML_Data() {
  this.data = null;
}

XML_Data.prototype = {
 GetXML: function() {
  $.ajax({
   type: "GET",
      url: "questions.xml",
   dataType: "html",
   success: function(xml) {
    this.data=xml;
    $(window).trigger("myAjaxEvent");
   } //close success
  });//close AJAX  
 },

 UseXML: function() {
  alert(this.data)
 }
};


$(document).ready( function () {
    var data = new XML_Data();
    $(window).bind("myAjaxEvent", function () {
      data.UseXML();
    });

    data.GetXML();

});


The code you have now is attempting to run synchronously (in order) using a non-blocking asynchronous API. The UseXML call happens before the GetXML call actually finishes doing its AJAX thing, because it's asynchronous.

You could write this in an asynchronous pattern (in which this.UseXML is called directly on success of the AJAX request), or a synchronous pattern (in which "async:false" is passed to the AJAX call). The asynchronous pattern is much more common in JavaScript development, as it is much more powerful, and synchronous requests block the UI in the browser by preventing script execution, but synchronous is much easier to do for little things.

See http://api.jquery.com/jQuery.ajax/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜