Demo.prototype.listMessages = function()

in authenticated-json-api/public/main.js [79:109]


Demo.prototype.listMessages = function(event) {
  this.$messageListButtons.removeClass('mdl-button--accent');
  $(event.target).parent().addClass('mdl-button--accent');
  this.$messageList.html('');
  this.$messageDetails.html('');

  // Make an authenticated GET request for a list of messages
  // Optionally specifying a category (positive, negative, neutral)
  var label = $(event.target).parent().text().toLowerCase();
  var category = label === 'all' ? '' : label;
  var url = category ? '/api/messages?category=' + category : '/api/messages';
  this.authenticatedRequest('GET', url).then(function(response) {
    var elements = response.map(function(message) {
      return $('<li>')
        .text(message.message)
        .addClass('mdl-list__item')
        .data('key', message.key)
        .on('click', this.messageDetails.bind(this));
    }.bind(this));

    // Append items to the list and simulate a click to fetch the first message's details
    this.$messageList.append(elements);

    if (elements.length > 0) {
      elements[0].click();
    }
  }.bind(this)).catch(function(error) {
    console.log('Error listing messages.');
    throw error;
  });
};