2015-10-03 3 views
0

Я пытаюсь создать отсортированную таблицу результатов поиска, возвращенных с YouTube. Я могу создать поисковую систему просто отлично, и я могу создать отсортированную таблицу. Но теперь я пытаюсь подключить их.Сортировка таблицы результатов поиска из API YouTube

Я знаю, что главная проблема заключается в том, что при загрузке страницы результатов нет; нет таблицы до тех пор, пока поиск не будет выполнен.

Я проверил это обсуждение, и я думаю, что есть кое-что для меня, но я не знаю, как его интегрировать.

Вот что я работаю с до сих пор:

app.js

function tplawesome(e, t) { 
res = e; 
for (var n = 0; n < t.length; n++) { 
    res = res.replace(/\{\{(.*?)\}\}/g, function(e, r) { 
     return t[n][r]; 
    }); 
} 
return res; 
} 

$(function() { 
$("form").on("submit", function(e){ 
    e.preventDefault(); 
    // prepare the request 
    var request = gapi.client.youtube.search.list({ 
     part: "snippet", 
     type: "video", 
     q: encodeURIComponent($("#search").val()).replace(/%20/g, "+"), 
     maxResults: 5, 
     publishedAfter: "2015-01-01T00:00:00Z", 
     relevanceLanguage: "en" 
    }); 
    // execute request 
    request.execute(function(response) { 
     // console.log(response); // test by logging to console 

     var results = response.result; 

     $("#results").html("");  // reset results 

     // loop through each returned item 
     $.each(results.items, function(index, item) { 
      console.log(item);  // test by logging to console 

      $.get("tpl/results-sortable-table.html", function(data) { 
       $("#results").append(tplawesome(data, 
        [{ 
         "title": item.snippet.title, 
         "description": item.snippet.description, 
         "channelTitle": item.snippet.channelTitle, 
         "publishedAt": item.snippet.publishedAt, 
        }] 
       )); 
      }); 
     }); 
     resetVideoHeight(); 
    }); 
}); 
$(window).on("resize", resetVideoHeight); // reset video height when window is resized 
}); 

function resetVideoHeight() { 
$(".video").css("height", $("#results").width() * 9/16); 
} 

function init() { 
gapi.client.setApiKey("");  // Removed on purpose 
gapi.client.load("youtube", "v3", function() { 
    // yt api is ready 
}); 
} 



// THE SORTING SCRIPT 

// I think I need to include something here that listens for when the table is populated. Is that right? 

// -------------------------------------------------------------------- 
// COMPARE OBJECT 
// -------------------------------------------------------------------- 

// Create a general "compare" object that will compare values in a table 
    var compare = { 
     name: function(a, b) {    // For genre and title (data-type = name) ... 
      a = a.replace(/^the /i, ''); // Remove "the" from start (^) of parameter a ... 
      b = b.replace(/^the /i, ''); // and parameter "b". 
      a = a.replace(/^a /i, '');  // Remove "a" from start (^) of parameter a ... 
      b = b.replace(/^a /i, '');  // and parameter "b". 
      a = a.replace(/^an /i, '');  // Remove "a" from start (^) of parameter a ... 
      b = b.replace(/^an /i, '');  // and parameter "b". 
      a = a.toUpperCase();   // Convert a to uppercase 
      b = b.toUpperCase();   // Convert b to uppercase 

      if (a < b) {     // If a is less than b ... 
       return -1;     // ???????? return -1 indicating a should be before b, ... 
      } else {      // otherwise ... 
       return a > b ? 1 : 0;  // return 1 if a is greater than b or ... 
      }        // return zero (if the are the same). 
     }, 

// -------------------------------------------------------------------- 
// DATE METHOD 
// -------------------------------------------------------------------- 
// Create a "date" method that will compare and sort two dares by using the date function to ... 
// convert string to date, and sort them based on their values. 

    date: function(a, b) {     // Add a method called date 
     a = new Date(a);     // New Date object to hold the date 
     b = new Date(b);     // New Date object to hold the date 

     // Compare dates and return result 
     return a > b ? 1 : 0;    // return 1 if a is greater than b or ... 
              // return zero (if the are the same).    
    }, 
}; 

// -------------------------------------------------------------------- 
// SORT TABLE SCRIPT 
// -------------------------------------------------------------------- 

$('.sortable').each(function() { 

// Establish variables 
var $table = $(this);      // The current sortable table. 
var $tbody = $table.find('tbody');   // Store this table's tbody in $tbody. 
var $thcontrols = $table.find('th');  // Store this table's th in $thcontrols. 
var rows = $tbody.find('tr').toArray();  // Store an array of tr's in rows. 

$thcontrols.on('click', function() { // When user clicks on a th 
    var $th = $(this);     // Get the th that was clicked on 
    var datasort = $th.data('sort'); // Get value of this th's data-sort attribute and store it in datasort. 
    var column;       // Declare the column variable. 

    // If selected item already has ascending or descending class, then it's already sorted so reverse contents. 
    if ($th.is('.ascending') || $th.is('.descending')) { // If th is .ascending or .descending ... 
     $th.toggleClass('ascending descending');   // switch their classes and ... 
     $tbody.append(rows.reverse());      // Reverse the headers array of rows. 
    } else {            // Otherwise perform a sort        
     // If compare object has method that matches the value of the data-type attribute for this column ... 
     if (compare.hasOwnProperty(datasort)) {  // Note: datasort is $th.data('sort') 
      column = $thcontrols.index(this);  // ... get the th's index number. 

      rows.sort(function(a, b) {     // Sort values in rows array. 
       a = $(a).find('td').eq(column).text(); // Find text of the td in the column in row a, ... 
       b = $(b).find('td').eq(column).text(); // find text of the td in the column in row b and ... 
       return compare[datasort](a, b);   // compare them. 
      }); 

     $th.addClass('ascending');       // Add .ascending to th and ... 
     $th.siblings().removeClass('ascending descending'); // remove asc or desc from all other headers. And ... 

      $tbody.append(rows); // Append the rows to the table body 
     } 
    } 
}); 
}); 

index.html

<!DOCTYPE html> 
<html lang="en"> 
<head>  
    <title>YouTube Search Engine</title> 
    <meta charset="UTF-8" />      
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
    <meta name="description" content="Awesome videos!" /> 
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"> 
    <link rel="stylesheet" href="css/style.css"> 
    <link rel="stylesheet" href="css/sort-table.css"> 
</head> 
<body> 
    <header> 
     <h1 class="w100 text-center"><a href="index.html">YouTube Viral Search</a></h1> 
    </header> 
    <div class="row"> 
     <div class="col-md-6 col-md-offset-3"> 
      <form action="#"> 
       <p><input type="text" id="search" placeholder="Type something..." autocomplete="off" class="form-control" /></p> 
       <p><input type="submit" value="Search" class="form-control btn btn-primary w100"></p> 
      </form> 


    <table class="sortable"> 
     <thead> 
      <tr> 
       <th data-sort="name">Title</th> 
       <th data-sort="name">Description</th> 
       <th data-sort="name">Channel Title</th> 
       <th data-sort="date">Published At</th> 
      </tr> 
     </thead> 
     <tbody id="results"> 
      <!-- results go here -->     
     </tbody> 
    </table>   

    </div> 
    </div> 

    <!-- scripts --> 
    <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> 
    <script src="js/app.js"></script> 
    <script src="https://apis.google.com/js/client.js?onload=init"></script> 

</body> 
</html> 

результаты трёхсортном-table.html

<tr onload="sort()" class="item"> 
    <td>{{title}}</td> 
    <td>{{description}}</td> 
    <td>{{channelTitle}}</td> 
    <td>{{publishedAt}}</td> 
</tr> 

Я знаю, что я просто поместил все, и кухня здесь, но мне все это известно, поэтому я не был уверен, что будет важно.

Благодаря всем, кто может помочь,

Aryadne

ответ

0

Я знаю, что основная проблема заключается в том, что при загрузке страницы нет результатов для сортировки; нет таблицы до тех пор, пока поиск не будет выполнен.

Несколько вещей, которые могут поставить вас в правильном направлении, и в решении вашей цитате:

  1. Убрать сортировку OnLoad из каждой строки
  2. обернуть свой код в функцию $('.sortable').each(function() {
  3. Вызовите эту функцию только тогда, когда все результаты добавлены на страницу. - сразу после того, как вы звоните resetVideoHeight();
+0

Так что это по-прежнему убивает меня. Вы были правы, что мне нужно было удалить нагрузку, и я завернул свой код в функцию, но я все еще в недоумении. – user37172