Loading...

Във форума е въведено ограничение, което позволява на потребителите единствено да разглеждат публикуваните въпроси.

nbglink avatar nbglink 9 Точки

Creating a Book Library with jQuery, AJAX and Kinvey -

Здравейте колеги,

 

Нещо не успявам да направя логиката за пускане на коментари на упражнението Creating a Book Library with jQuery, AJAX and Kinvey.

С динамичния DOM го докарах до някъде, но не мога да опрделя начин за получаване на данните необходими във функцията addBookComment(bookData, commentText, commentAuthor) (може би нещо не си е на мястото), мъчих го дота време, но не успях да намеря решение, може би липсва някое звено от нишката. ;)

https://github.com/nbglink/SoftwareTechnologies-2016/tree/master/06BookLibrary

Мерси!

 

 

 

Тагове:
1
Софтуерни технологии 29/06/2016 17:23:56
ParushevIvan avatar ParushevIvan 0 Точки

 

По време на генениране на списъкът с книги, данните за всяка една от тях (book._id, book.title и т.н.), които се съдържат в променливата book, се запазват като стрингосан обект в скрито input поле на формата за коментари.

var bookString = JSON.stringify(book);
var commentForm = $('<form class="formComment" style="display: none">')
    .append($("<input type='hidden' class='bookData' value='"+bookString+"' />"))
    .append($('</form>'));

 

При натискане на бутон "submit commet" стрингосаните данни от книгата се парват в JSON обект и се изпащат заедно с данните от коментара като аргументи на функцията addBookComment(bookJSON, commentText, commentAuthor).

let bookJSON = JSON.parse(bookData);

 

Понеже има малко разминаване откода в .doc файла и кода от видео лекцията на Наков е необходимо да се направи малка корекция на функцията addBookComment(). Този ред:

bookData.comments.push({text: commentText, author: commentAuthor});

 трябва да се приведе в следния вид:

bookData.comments.push({commentAuthor: commentAuthor, commentText: commentText});

 

Целият код на функцията за зареждане на книгите изглежда така: 

function showListBooksView() {
    showView('viewListBooks');
    $("#books").text('');
    let booksUrl = kinveyServiceUrl + "appdata/" + kinveyAppID + "/books";
    let authHeaders = {
        "Authorization": "Kinvey " + sessionStorage.authToken
    };
    $.ajax({
        method: "GET",
        url: booksUrl,
        headers: authHeaders,
        success: booksLoaded,
        error: showAjaxError,
    });
    function booksLoaded(books, status) {
        showInfo("Books loaded.");

        let booksTable = $("<table>").append($("<tr>")
                    .append($('<th>Title</th>'))
                    .append($('<th>Author</th>'))
                    .append($('<th>Description</th>'))
                );

        for (let book of books) {
            var bookTitle = book.title;
            booksTable.append($("<tr>")
                    .append($('<td></td>').text(book.title))
                    .append($('<td></td>').text(book.author))
                    .append($('<td></td>').text(book.description))
            );

            var bookString = JSON.stringify(book);

            var commentForm = $('<form class="formComment" style="display: none">')
                    .append($('<label for="commentAuthor">Your Name: </label>'))
                    .append($('<input type="text" id="commentAuthor"/>'))
                    .append($('<label for="commentText">Your comment: </label>'))
                    .append($('<input type="text" id="commentText"/>'))
                    .append($("<input type='hidden' class='bookData' value='"+bookString+"' />"))
                    .append($('<button class="addComment" type="button" onclick="addComment()" >Add Comment</button>'))
                    .append($('<input id="Cancel" type="button" value="Cancel" onclick="cancelComment()"/>'))
                    .append($('</form>'));
            var comWrap = $('<div class="comment-wrap"></div>');

            if (book.comments != null){
                for (var i=0; i < book.comments.length; i++){
                    var comment = book.comments[i];
                    let comText = $('<div></div>').text('"' + comment.commentText + '"');
                    let comAuth = $('<div><i>-- ' + comment.commentAuthor + ' --</i></div>');

                    comWrap.append(comText, comAuth);
                }
            }

            comWrap.append($('<a href="#formComment" class="more" onclick="showFormComments()">Add Comment</a>'));
            comWrap.append(commentForm);
            booksTable.append($("<tr>")
                .append($('<td colspan="3"></td>').append(comWrap))
            );
        }
        $("#books").append(booksTable);//video time point: 2:12:22

    }
}

function showFormComments() {
    let a = document.activeElement; // in this case it is the <a> element
    a.style.display = 'none';
    a.nextElementSibling.style.display = 'inline-block'; // nextElementSibling is the hidden form
}

function addComment() {
    let buttonFormSubmit = document.activeElement;
    let parent = buttonFormSubmit.parentNode; //stores the parent node of the active element
    /*
     var buttonIndex = Array.prototype.indexOf.call(parent.children, buttonFormSubmit);
     checks the index of the active element
     which in our case was [5] for the formComment submit button
     */
    let nodes = parent.childNodes; // creates an array of all the child nodes
    let commentAuthor = nodes[1].value;
    let commentText = nodes[3].value;
    let bookData = nodes[4].value;
    let bookJSON = JSON.parse(bookData); //converts the bookData from string format to JSON
    addBookComment(bookJSON, commentText, commentAuthor);
}

function cancelComment() {
    let buttonFormCancel = document.activeElement;
    let parent = buttonFormCancel.parentNode;
    parent.style.display = 'none';
    parent.previousElementSibling.style.display = 'inline-block';
}

function addBookComment (bookData, commentText, commentAuthor) {
    let booksUrl = kinveyServiceUrl + "appdata/" + kinveyAppID + "/books";
    let authHeaders = {
        "Authorization": "Kinvey " + sessionStorage.authToken,
        "Content-type": "application/Json"
    };
    if (!bookData.comments) {
        bookData.comments = [];
    }
    bookData.comments.push({commentAuthor: commentAuthor, commentText: commentText});
    $.ajax({
        method: "PUT",
        url: booksUrl + "/" + bookData._id,
        headers: authHeaders,
        data: JSON.stringify(bookData),
        success: addBookCommentSuccess,
        error: showAjaxError
    });
    function addBookCommentSuccess(data, status) {
        showListBooksView();
        showInfo('Book comment added.')
    }
}

 

0
06/08/2016 22:47:20
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.