Cremix_hellven
Cremix_hellven

Reputation: 995

When this function gets this parameter?

I'm checking a piece of code which purpose is to print a movie list:

HTML CODE

<h1>My new Website</h1>
    <form action="formHandler.php" method="GET" id="movieSearchForm">
        <input name="query" type="search" id="search" placeholder="Find a Movie">
        <button>
            Search
        </button>
    </form>
<div id="resultList"></div>
<div id="movieList"></div>

EVENT HANDLER

$('#movieSearchForm').on('submit', function (event) {
    event.preventDefault();
    var movieTitle = $('#movieSearchForm input').val();

    requestApi(movieTitle, myApp);
});           

API VAR

var apiUrl = 'http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=j23zuzdpapq9ny3watvc9kja';¬

REQUEST API

var requestApi = function (query, callback) {
    $.ajax({
      url: apiUrl,
      data: {
        q: query
      },
      dataType: 'jsonp'
   }).success(callback);
}

MY APP FUNCTION

var myApp = function (response) {
    var movieListData = response.movies;

    var movieList = movieListData.map(function (movieItem) {
        return itemHtml(movieItem.posters.thumbnail, movieItem.title);
    });     

    $('#movieList').get(0).innerHTML = [
      '<ul>',
          movieList.join(''),
       '</ul>'
    ].join('');
};

So, requestApi gets the movie list needed and myApp formats it and inserts it in the web. What I don't understand is how myApp gets response parameter. Any idea? And one question more, if I want that myApp gets two parameters, what should I change?:

Upvotes: 0

Views: 85

Answers (2)

Joe
Joe

Reputation: 15802

response is provided by jQuery: api.jquery.com/jQuery.ajax - scroll down to "success" and it says that you get Function( PlainObject data, String textStatus, jqXHR jqXHR ) - this is a function which gets an object as its first param, a string as the second and the xhr object as the third.

To make your callback take 2 parameters, you can do this:

$('#movieSearchForm').on('submit', function (event) {
    event.preventDefault();
    var movieTitle = $('#movieSearchForm input').val();

    requestApi(movieTitle, function(response) { myApp(response, anotherParam, yetAnotherParam); });
});

then just update myApp to expect them:

function myApp(response, aParam, bParam) {

Upvotes: 2

KJ Price
KJ Price

Reputation: 5984

So, I'm assuming that requestApi accepts two parameters: movie title (a string) and callback (a callback function). Once requestApi returns with some data, it will call the callback function similar to doing something like:

callbackFunction({title:"stuff", length:"1:09:30"});

Where callbackFunction is your myApp function and your response parameter will get all of that nice JSON that was passed from callbackFunction.

Welcome to Async Javascript!

Upvotes: 1

Related Questions