LOADING...

Preview

Pen ID
Unlock Campus Themeforest adv

 

Code

StarWars People

 
Name Skin Color Birth Year Gender
- search to see some results -
CSS
body {
  margin: 1.5rem;
}

h3, form {
  margin-bottom: 1.5rem;
}
JS
/**
 * Exercise:
 *
 * Create a class that sends a request to the Star Wars API,
 * when the search form is send. Use the search feature
 * on the "people" endpoint of the API, that you will
 * find in the documentation.
 *
 * The returned data should then be written to the table.
 * 
 * Please Remove the demo data, that is only there to show
 * you what it should look lile.
 *
 * The API documentation:
 * https://swapi.co/documentation
 */
class InvalidArgumentException {
  constructor(message) {
    this.message = message;
  }
}

class HttpResponseException {
  constructor(code, message, response) {
    this.code = code;
    this.message = message;
    this.response = response;
  }
}

class StarWarsPeopleSearch {
  constructor(options) {
    if (typeof options === 'undefined') {
      throw new InvalidArgumentException('Missing parameter "options".');
    }
    
    this.requiredElements  = ['form', 'input', 'button', 'table'];
    this.elements = {};
    
    this.requiredElements.forEach((item) => {
      if (!options.hasOwnProperty(item)) {
        throw new InvalidArgumentException(`Missing option "${ item }".`);
      }
      
      const jQueryElement = $(options[ item ]);
      
      if (jQueryElement.length !== 0) {
        this.elements[ item ] = jQueryElement;
      } else {
        throw new InvalidArgumentException(`The "${ item } element cannot be not found using selector: ${ options[ item ] }`);
      }
    });
    
    this.isLoading = false;
    this.registerFormHandler();
  }
  
  search(query, callback) {
    if (typeof query !== 'string'
        || query.length < 1) {
      throw new InvalidArgumentException('Parameter "query" is missing or of a wrong type.');
    }
    
    if ((callback instanceof Function) === false) {
      throw new InvalidArgumentException('Parameter "callback" has to be a function.');
    }
    
    const searchParam = encodeURIComponent(query);
    this.isLoading = true;
    this.toggleButton();
    
    $.get(`https://swapi.co/api/people/?search=${searchParam}`)
      .done((data) => {
        callback(data);
      })
      .fail(function(response) {
        throw new HttpResponseException(response.status, 'API Error', response);
      }).always(() => {
        this.isLoading = false;
        this.toggleButton();
      });
  }
  
  registerFormHandler() {    
    this.elements.form.on('submit', (e) => {
      e.preventDefault();
      
      if (this.isLoading === true) {
        return;
      }
      
      const query = this.elements.input.val().trim();
      
      if (query.length !== 0) {
        this.search(query, (data) => {
          const tableBody = this.elements.table.find('tbody');
          
          if (data.count === 0) {
            tableBody.html('')
                     .append('- no results found -');
          } else {
            tableBody.html('');
            
            data.results.forEach((item) => {
              tableBody.append(`
                
                  ${item.name}
                  ${item.skin_color}
                  ${item.birth_year}
                  ${item.gender}
                
              `);
            });
          }
        });
      }
    });
  }
  
  toggleButton() {
    if (typeof this.elements.button.attr('disabled') === 'undefined') {
      this.elements.button.prepend(' ');
      this.elements.button.attr('disabled', 'disabled');
    } else {
      this.elements.button.find('.fa').remove();
      this.elements.button.removeAttr('disabled');
    }
  }
}

const peopleSearch = new StarWarsPeopleSearch({
  "form": "#people-form",
  "input": "#people-name",
  "button": "#people-button",
  "table": "#people-table"
});
Term
Wed, 12/27/2017 - 06:58

Related Codes

Pen ID
Pen ID
Pen ID
Square Adv