반응형
윅스 (Wix) 코딩 강의 중급 (Intermediate) - 기프트 선물 퀴즈 만들기 (Gift Quiz) - 윅스 쇼핑몰, 스토어 (Wix Stores)
강의 내용 요약
다음의 예제는 Wix 윅스 무료 홈페이지 만들기의 자바스크립트 (Javascript) 코딩 기능을 활용할 수 있는 Corvid by Wix (윅스 코딩 - 콜비드) 를 활용하여 만듭니다.
웹사이트 방문자들에게 퀴즈 문제와 함께 퀴즈 문제에 맞는 추천 상품을 찾을 수 있도록 도와주는 기능을 만듭니다.
강의 내용 만드는법
만들고자 하는 윅스 사이트에 다음과 같은 구성 요소들이 필요합니다.
- 데이터베이스 컬렉션 (productsKeywords)
- 슬라이드쇼
- 반복레이아웃 / 리피터
- 이미지
- 텍스트
코드 (Code)
Gift Quiz
//-------------Imports-------------//
import wixData from 'wix-data';
//-------------Global Variables-------------//
// List of selected answers.
const selectedAnswers = [];
// List of IDs of all the answer buttons.
const quizAnswersIds = ["bestie", "girlfriend", "myself",
"surpriseMe", "accessories", "clothing", "beauty",
"surpriseMe2", "gold", "red", "lavender"
];
// Number of questions plus one for the results.
let numberOfSlides;
//-------------Page Setup-------------//
$w.onReady(() => {
// Set the global numberOfSlides variable from the slideshow length.
numberOfSlides = $w('#quizSlides').slides.length;
// For each answer button:
quizAnswersIds.forEach(answer => {
// Set the action that occurs when a user clicks the answer button.
$w(`#${answer}`).onClick(() => {
// Add the answer to the global selected answers list.
selectedAnswers.push(answer);
// Move to the next slide.
$w('#quizSlides').next();
})
})
});
//-------------Quiz Finish-------------//
// Set the action that occurs when a user is moved to the next slide.
export async function quizSlides_change(event, $w) {
// If the quiz is finished:
if (isQuizFinished()) {
// Get the keywords associated with each product by calling the getKeywordsPerProduct() function.
let quizProducts = await getKeywordsPerProduct();
// For each selected answer:
selectedAnswers.forEach(answer => {
// Filter out the products that do not match the answer.
quizProducts = filterProductsPerAnswer(quizProducts, answer);
});
// Extract the product IDs from the filtered product.
quizProducts = quizProducts.map(quizProduct => quizProduct.productId);
// Get a random list from the remaining filtered products.
quizProducts = getRandomItemsFromArray(quizProducts, numberOfSlides);
// Populate the recommended products repeater with the product data that corresponds to the randomly selected products.
$w('#recommendedProducts').data = await getProductsData(quizProducts);
}
}
// Checks if the quiz has been completed.
function isQuizFinished() {
// Check if the current slide is the last slide.
return $w('#quizSlides').currentIndex === numberOfSlides - 1;
}
// Get the keywords associated with each product.
async function getKeywordsPerProduct() {
// Query the "productsKeywords" collection for the product keywords.
let productsKeywords = await wixData.query("productsKeywords").find();
// Extract the items from the query results.
productsKeywords = productsKeywords.items;
// Process the returned item data to make it easier to work with.
productsKeywords = productsKeywords.map(item => {
return {
productId: item.product,
keywords: item.keywords.split(",")
}
});
// Return the processed item data.
return productsKeywords;
}
// Filter out products that don't match the specified answer.
function filterProductsPerAnswer(quizProducts, answer) {
// Use the JavaScript filter() function to filter out products that don't match the specified answer.
const filteredProducts = quizProducts.filter(quizProduct => {
return quizProduct.keywords.includes(answer)
});
// Return the filtered product list.
return filteredProducts;
}
// Get a specified number of random items from the specified array.
function getRandomItemsFromArray(productsArr, numberOfItems){
// List for storing the randomly selected products.
const productsIds = [];
// Number of products in the specified array.
const numberOfProducts = productsArr.length;
// For specified the number of items or the number of products that were specified, whichever is lower:
for (let i = 0; i < (numberOfItems && i < numberOfProducts); i++){
// Get a random valid index.
const randomIndex = getRandomInt(0, numberOfProducts -1 );
// Add the product at that random index to the list of selected products.
productsIds.push(productsArr[randomIndex]);
// Remove the already selected product from the list of products to select from.
productsIds.splice(randomIndex, 1);
}
// Return the randomly selected products.
return productsIds;
}
// Get a random number between two specified values.
function getRandomInt(min, max) {
// Use JavaScript math functions to get a random number between two specified values.
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Get the product data associated with the specified product IDs.
async function getProductsData(productsIds) {
// Query the "Products" collection for products whose ID is one of the specified IDs.
const productsData = await wixData.query("Stores/Products")
.hasSome("_id", productsIds)
.find();
// Return the matching products.
return productsData.items;
}
// Set up each item in the recommended products repeater when it receives data as the quiz is finished.
export function recommendedProducts_itemReady($item, itemData, index) {
// Populate the elements from the current item's data.
$item('#name').text = itemData.name;
$item('#image').src = itemData.mainMedia;
$item('#image').link = itemData.productPageUrl;
$item('#price').text = itemData.formattedPrice;
}
Site Code
$w.onReady(function () {
});
API
Corvid by Wix (윅스 코딩 - 콜비드) 개발자 모드/도구 활성화하는 방법
윅스 (Wix) 코딩 - 개발자 도구를 활성화하기 (Wix Code: How to Enable Developer Tools)
연관된 토픽)
윅스 (Wix) 코딩 중급 (Intermediate) - 다크 모드, 나이트 모드 만들기 (Dark Mode) - 상호작용 (Interactions)
윅스 (Wix) 코딩 고급 (Advanced) - 커스텀 제품 만들기 2 (Print on Demand) - 윅스 쇼핑몰, 스토어 (Wix Stores)
윅스 홈페이지 만들기 101
윅스 (Wix) 홈페이지 만들기 101 - E-Book - Index
출처 :
콜비드 - 윅스 코딩 (Corvid - Wix coding)
반응형
댓글