mrtriangle
mrtriangle

Reputation: 544

Refactoring jQuery in JS issues

I use jQuery frequently but I have realized that I need to understand the underlying Javascript better. I have worked out the AJAX part but am stuck on the nested functions. Any help is greatly appreciated.

document.onreadystatechange = function() {
  var state = document.readyState;

  if (state == 'interactive') {
    $('#button').on("click", function() {
      $.getJSON(apiurl, function(json) {

        $.each(json.photos.photo, function(i, myresult) {
          apiurl_size = "https//api/myresult";
          $.getJSON(apiurl_size, function(size) {
            $.each(size.sizes.size, function(i, myresult_size) {
              if (myresult_size.width == selected_size) {
                $("#results").append('<p class="col-md-4"><a href="" ><img src="' + myresult_size.source + '"/></a></p>');
              }
            })
          })
        });
      });
    });
  } else if (state == 'complete') {
    document.getElementById('complete');
  }
}

What I want to know:

  1. how to grab the id selector in $('button') since document.getElementById('button') returns the entire element but I cannot enact the .on click functionalitiy

  2. breaking the .getJSON function out into a pure JS reusable function

Upvotes: 0

Views: 49

Answers (1)

Barmar
Barmar

Reputation: 780798

  1. $("#button").on("click", cb_function) is analogous to document.getElementById("button").addEventListener("click", cb_function). If you were using a selector that can match multiple elements, it's similar except that it loops over all the returned elements to add event listeners to all of them.

  2. $.getJSON(URL, cb_function) creates an AJAX request to the URL whose onreadystatechange callback function essentially does:

    1. call JSON.parse() on the response.
    2. Call cb_function with the result of the parse.

A simple version would be like:

function getJSON(url, cb_function) {
    var xhr = new XMLHTTPRequest();
    xhr.open("GET", url);
    xhr.onreadystatechange = function() {
        if (xhr.readystate == 4 && xhr.status == 200) {
            cb_function(JSON.parse(xhr.responseText));
        }
    }
    xhr.send();
    return xhr;
}

The real $.getJSON allows you to supply parameters to the URL, and it automatically converts from an object to the appropriate URL-encoded string to add as URL parameters. But neither of your calls has data parameters, so this definition should work for you.

Upvotes: 1

Related Questions