Javascript.RU

Создать новую тему Ответ
 
Опции темы Искать в теме
  #1 (permalink)  
Старый 31.08.2016, 13:08
Новичок на форуме
Отправить личное сообщение для Wildcat Посмотреть профиль Найти все сообщения от Wildcat
 
Регистрация: 31.08.2016
Сообщений: 2

Вызов функции для случайного выбора категории [Решено]
Прошу помощи по учебной задаче.
Поскольку только изучаю JS, к сожалению, знаний не хватает для самостоятельного решения.
Проблема: неясно, что нужно дать функции chooseRandomCategory() (STEP 2) в качестве параметра, чтобы сайт генерировал HTML-страницу со случайно выбранной категорией по нажатию на плитку "Specials". Пожалуйста, помогите разобраться.

UPD. Решено таким образом:

// TODO: STEP 2: Here, call chooseRandomCategory, passing it retrieved 'categories'
      // Pay attention to what type of data that function returns vs what the chosenCategoryShortName
      // variable's name implies it expects.
      var chosenCategoryShortName = chooseRandomCategory(categories);
      
      // TODO: STEP 3: Substitute {{randomCategoryShortName}} in the home html snippet with the
      // chosen category from STEP 2. Use existing insertProperty function for that purpose.
      // Look through this code for an example of how to do use the insertProperty function.
      // WARNING! You are inserting something that will have to result in a valid Javascript
      // syntax because the substitution of {{randomCategoryShortName}} becomes an argument
      // being passed into the $dc.loadMenuItems function. Think about what that argument needs
      // to look like. For example, a valid call would look something like this:
      // $dc.loadMenuItems('L')
      // Hint: you need to surround the chosen category short name with something before inserting
      // it into the home html snippet.
      // 

      var homeHtmlToInsertIntoMainPage = insertProperty(homeHtml, "randomCategoryShortName", "'" + chosenCategoryShortName.short_name + "'");


// TODO: STEP 2: Here, call chooseRandomCategory, passing it retrieved 'categories'
      // Pay attention to what type of data that function returns vs what the chosenCategoryShortName
      // variable's name implies it expects.
var chosenCategoryShortName = chooseRandomCategory(?????????);


Код полностью:
(function (global) {

var dc = {};

var homeHtmlUrl = "snippets/home-snippet.html";
var allCategoriesUrl = 
  "https://davids-restaurant.herokuapp.com/categories.json";
var categoriesTitleHtml = "snippets/categories-title-snippet.html";
var categoryHtml = "snippets/category-snippet.html";
var menuItemsUrl = 
  "https://davids-restaurant.herokuapp.com/menu_items.json?category=";
var menuItemsTitleHtml = "snippets/menu-items-title.html";
var menuItemHtml = "snippets/menu-item.html";

// Convenience function for inserting innerHTML for 'select'
var insertHtml = function (selector, html) {
  var targetElem = document.querySelector(selector);
  targetElem.innerHTML = html;
};

// Return substitute of '{{propName}}' 
// with propValue in given 'string' 
var insertProperty = function (string, propName, propValue) {
  var propToReplace = "{{" + propName + "}}";
  string = string
    .replace(new RegExp(propToReplace, "g"), propValue);
  return string;
}

// On page load (before images or CSS)
document.addEventListener("DOMContentLoaded", function (event) {
  
// TODO: STEP 0: Look over the code from 
// *** start *** 
// to 
// *** finish *** 
// below.
// We changed this code to retrieve all categories from the server instead of
// simply requesting home HTML snippet. We now also have another function
// called buildAndShowHomeHTML that will receive all the categories from the server
// and process them: choose random category, retrieve home HTML snippet, insert that
// random category into the home HTML snippet, and then insert that snippet into our
// main page (index.html).
//
// TODO: STEP 1: Substitute [...] below with the *value* of the function buildAndShowHomeHTML, 
// so it can be called when server responds with the categories data.

// *** start ***
// On first load, show home view
showLoading("#main-content");
$ajaxUtils.sendGetRequest(
  allCategoriesUrl, 
  buildAndShowHomeHTML, // ***** <---- TODO: STEP 1: Substitute [...] ******
  true); // Explicitely setting the flag to get JSON from server processed into an object literal
});
// *** finish **

// Builds HTML for the home page based on categories array
// returned from the server.
function buildAndShowHomeHTML (categories) {
  
  // Load home snippet page
  $ajaxUtils.sendGetRequest(
    homeHtmlUrl,
    function (homeHtml) {

      // TODO: STEP 2: Here, call chooseRandomCategory, passing it retrieved 'categories'
      // Pay attention to what type of data that function returns vs what the chosenCategoryShortName
      // variable's name implies it expects.
var chosenCategoryShortName = chooseRandomCategory(?????????);
      
      // TODO: STEP 3: Substitute {{randomCategoryShortName}} in the home html snippet with the
      // chosen category from STEP 2. Use existing insertProperty function for that purpose.
      // Look through this code for an example of how to do use the insertProperty function.
      // WARNING! You are inserting something that will have to result in a valid Javascript
      // syntax because the substitution of {{randomCategoryShortName}} becomes an argument
      // being passed into the $dc.loadMenuItems function. Think about what that argument needs
      // to look like. For example, a valid call would look something like this:
      // $dc.loadMenuItems('L')
      // Hint: you need to surround the chosen category short name with something before inserting
      // it into the home html snippet.
      // 

      var homeHtmlToInsertIntoMainPage = insertProperty(homeHtml, "randomCategoryShortName", chosenCategoryShortName);

      // TODO: STEP 4: Insert the the produced HTML in STEP 3 into the main page
      // Use the existing insertHtml function for that purpose. Look through this code for an example
      // of how to do that. 

      insertHtml("#main-content", homeHtmlToInsertIntoMainPage);


    },
    false); // False here because we are getting just regular HTML from the server, so no need to process JSON.
}


// Given array of category objects, returns a random category object.
function chooseRandomCategory (categories) {
  // Choose a random index into the array (from 0 inclusively until array length (exclusively))
  var randomArrayIndex = Math.floor(Math.random() * categories.length);

  // return category object with that randomArrayIndex
  return categories[randomArrayIndex];
}

// Builds HTML for the categories page based on the data
// from the server
function buildAndShowCategoriesHTML (categories) {
  // Load title snippet of categories page
  $ajaxUtils.sendGetRequest(
    categoriesTitleHtml,
    function (categoriesTitleHtml) {
      // Retrieve single category snippet
      $ajaxUtils.sendGetRequest(
        categoryHtml,
        function (categoryHtml) {
          // Switch CSS class active to menu button
          switchMenuToActive();

          var categoriesViewHtml = 
            buildCategoriesViewHtml(categories, 
                                    categoriesTitleHtml,
                                    categoryHtml);
          insertHtml("#main-content", categoriesViewHtml);
        },
        false);
    },
    false);
}


// Using categories data and snippets html
// build categories view HTML to be inserted into page
function buildCategoriesViewHtml(categories, 
                                 categoriesTitleHtml,
                                 categoryHtml) {
  
  var finalHtml = categoriesTitleHtml;
  finalHtml += "<section class='row'>";

  // Loop over categories
  for (var i = 0; i < categories.length; i++) {
    // Insert category values
    var html = categoryHtml;
    var name = "" + categories[i].name;
    var short_name = categories[i].short_name;
    html = 
      insertProperty(html, "name", name);
    html = 
      insertProperty(html, 
                     "short_name",
                     short_name);
    finalHtml += html;
  }

  finalHtml += "</section>";
  return finalHtml;
}

// Builds HTML for the single category page based on the data
// from the server
function buildAndShowMenuItemsHTML (categoryMenuItems) {
  // Load title snippet of menu items page
  $ajaxUtils.sendGetRequest(
    menuItemsTitleHtml,
    function (menuItemsTitleHtml) {
      // Retrieve single menu item snippet
      $ajaxUtils.sendGetRequest(
        menuItemHtml,
        function (menuItemHtml) {
          // Switch CSS class active to menu button
          switchMenuToActive();
          
          var menuItemsViewHtml = 
            buildMenuItemsViewHtml(categoryMenuItems, 
                                   menuItemsTitleHtml,
                                   menuItemHtml);
          insertHtml("#main-content", menuItemsViewHtml);
        },
        false);
    },
    false);
}

global.$dc = dc;

})(window);

Последний раз редактировалось Wildcat, 31.08.2016 в 17:47. Причина: Найдено решение
Ответить с цитированием
  #2 (permalink)  
Старый 31.08.2016, 15:10
Аватар для ksa
ksa ksa вне форума
CacheVar
Отправить личное сообщение для ksa Посмотреть профиль Найти все сообщения от ksa
 
Регистрация: 19.08.2010
Сообщений: 14,123

Сообщение от Wildcat
только изучаю JS
Что-то кода многовато для "только изучающего"...
Ответить с цитированием
  #3 (permalink)  
Старый 31.08.2016, 16:21
Новичок на форуме
Отправить личное сообщение для Wildcat Посмотреть профиль Найти все сообщения от Wildcat
 
Регистрация: 31.08.2016
Сообщений: 2

Сообщение от ksa Посмотреть сообщение
Что-то кода многовато для "только изучающего"...
Это учебная задача Coursera, в которой мне, всего-навсего, нужно выполнить 4 шага. Т.е., поправить буквально несколько строк.
Три шага более-менее понял как сделать, а во втором плотно застрял...
Ответить с цитированием
  #4 (permalink)  
Старый 01.09.2016, 06:49
Профессор
Отправить личное сообщение для warren buffet Посмотреть профиль Найти все сообщения от warren buffet
 
Регистрация: 08.07.2016
Сообщений: 1,332

Скажи мил человек, какой дебил тебя заставляет изучать ява-скрипт? Пока ты выучишься, уже новая инкарнация интерпретатора для браузеров появится, а самих этих интерпретаторов разных - как грязи.

Скажи ему, тому кто тебя учит, учиться на паскале или фортране - на мертвых языках, как учатся медики на латыни. Мертвый язык - это вечность. А жаба скрипучая упрыгает от тебя как только так сразу.
Ответить с цитированием
Ответ



Опции темы Искать в теме
Искать в теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
О видимости функции внутри другой функции, рекурсивный вызов DanK Node.JS 1 24.08.2016 20:32
Вызов функции внутри другой функции. Win32Sector Events/DOM/Window 1 12.12.2015 20:28
поиск классов внутри тега yozuul jQuery 24 14.06.2013 22:00
Вызов функции из скрытого iframe Beer75 Общие вопросы Javascript 2 05.06.2013 21:36
вызов метода return для функции-родителя evgen28 Общие вопросы Javascript 17 22.01.2009 15:46