Feel Physics
Feel Physics

Reputation: 2783

class initialization with getting json by ajax always fails

I am newbie of JavaScript. I want to make a class which communicate to Flickr Web API with Ajax when initialized.

Photo2.js

  var Photo2;

  Photo2 = (function() {

    Photo2.prototype.json = null;

    function Photo2() {
      $.getJSON('http://www.flickr.com/services/rest/?jsoncallback=?', {
        format: 'json',
        method: 'flickr.photos.search',
        api_key: '7965a8bc5a2a88908e8321f3f56c80ea',
        user_id: '29242822@N00',
        per_page: '100'
      }, function(data) {
        this.json = data.photos.photo;
      });
    }

    return Photo2;

  })();

But when initialized as photo2 = new Photo2 this does not have photo2.json.

Thank you for your kindness.

Upvotes: 2

Views: 177

Answers (1)

dreame4
dreame4

Reputation: 779

You should really rewrite your code. It's complicated and hard to figure out what you'd like to achieve.

First of all, getting data from server is asynchronous so you cannot be sure that after creating an instance of Photo2 json property will be defined.

Next things is that it's really bad idea to make server call while initializing an object. I advice you following solution:

(function() {
  var Photo2 = function(callback) {
    this.json = null;
  };

  Photo2.prototype.getData =  function(successCallback) {
    var self = this;

    $.getJSON('http://www.flickr.com/services/rest/?jsoncallback=?', {
        format: 'json',
        method: 'flickr.photos.search',
        api_key: '7965a8bc5a2a88908e8321f3f56c80ea',
        user_id: '29242822@N00',
        per_page: '100'
      }, function(data) {
        self.json = data.photos.photo;
        typeof successCallback == 'function' && successCallback();
      }); 
  };

  var photo = new Photo2();
  photo.getData(function successCallback() {
    console.log('Data loaded', photo.json);
  });
}).call(this);

Working demo here: http://jsbin.com/ureyas/1/edit

Upvotes: 2

Related Questions