Использование подтверждения с функцией-прототипом Jquery и другой функцией - PullRequest
0 голосов
/ 07 февраля 2019

Я работаю над комментариями в моем приложении, у меня есть функция-прототип, которая предупреждает о создании комментария ... однако я хочу изменить его на подтверждающее сообщение, поэтому, если я нажму "Отмена", комментарий не будетвывешенный.На данный момент он публикуется независимо от того, что я нажимаю.Вот мой код для создания комментария:

$(function createComment() {
  $("#new_comment").on("submit", function(e) {
    e.preventDefault();

    const values = $(this).serialize()

    $.post(this.action, values).success(function(response) {
      const newComment = new Comment(response);

      newComment.commentConfirm();

      $('div.comments_container').append('<div class="new_comment_' + `${response.id}` + '"> </div>')

      $('div.new_comment_'+ `${response.id}`).append('<h3 class="cheading">' + newComment.user.name + ' gives ' + newComment.rating + ' out of 5 stars! </h3>')
      $('div.new_comment_'+ `${response.id}`).append('<p class="cdescription">' + newComment.description + '</p>')
      $('div.new_comment_'+ `${response.id}`).append('<a class="ecomment" href="/recipes/' + `${response.recipe_id}` + '/comments/' + `${response.id}` + '/edit">Edit</a>' + " ")
      $('div.new_comment_'+ `${response.id}`).append('<a class="dcomment" rel="nofollow" data-method="delete" href="/comments/' + `${response.id}` + '">Delete</a>')

    });

$('form#new_comment')[0].reset();

  });
});

, а вот функция-прототип:

Comment.prototype.commentConfirm = function() {
  var c = confirm('You are about to comment: "' + this.description + '" and give a rating of: ' +  this.rating + ' stars');
    if (c == true){
      return true;
    } 
    else {
      return false;
    }
}

function Comment(comment) {
  this.description = comment.description;
  this.rating = comment.rating;
  this.user = comment.user;
}

-

- Итак, после изменения моего кода в спецификациипредложенный ответ и перемещение материала, чтобы заставить его работать, вот то, что я имею до сих пор.Параметр commentConfirm вызывается перед публикацией, но независимо от подтверждения или отмены он продолжает публиковать комментарий, однако не добавляет его напрямую;он возвращает мне JSON-объект комментария.Вот код:

$(function createComment() {
  $("#new_comment").on("submit", function(e) {

    const values = {
      description: $('#comment_description').val(),
      rating: $('#comment_rating').val()
    };

    const newComment = new Comment(values);
    newComment.commentConfirm();

  });
});

function Comment(comment) {
  this.description = comment.description;
  this.rating = comment.rating;
}

Comment.prototype.commentConfirm = function(e) {
  let doIt = confirm(`You are about to comment: "${this.description}" and give a rating of: ${this.rating} stars`);
  if(!doIt)
    return;

  let params = {
    'comment[description]': this.description,
    'comment[rating]': this.rating
  };

  $.post(this.action, params).success(function(response) {

    $('div.comments_container').append('<div class="new_comment_' + `${response.id}` + '"> </div>')

      $('div.new_comment_'+ `${response.id}`).append('<h3 class="cheading">' + `${response.user.name}` + ' gives ' + `${response.rating}` + ' out of 5 stars! </h3>')
      $('div.new_comment_'+ `${response.id}`).append('<p class="cdescription">' + `${response.description}` + '</p>')
      $('div.new_comment_'+ `${response.id}`).append('<a class="ecomment" href="/recipes/' + `${response.recipe_id}` + '/comments/' + `${response.id}` + '/edit">Edit</a>' + " ")
      $('div.new_comment_'+ `${response.id}`).append('<a class="dcomment" rel="nofollow" data-method="delete" href="/comments/' + `${response.id}` + '">Delete</a>')

      $('form#new_comment')[0].reset();
    });
};

1 Ответ

0 голосов
/ 08 февраля 2019

Как я упоминал в комментариях, вам нужно вывернуть свою логику наизнанку, чтобы вызов confirm мог произойти до $.post.

Сначала вам нужно изменить способ распаковки формы.в вашем обработчике отправки:

$("#new_comment").on("submit", function(e) {
  const values = {
    description: $('#comment_description').val(),
    rating: $('#comment_rating').val()
  };

  const newComment = new Comment(values);
  newComment.commentConfirm();

  $('form#new_comment')[0].reset();
});

В основном так же, как у вас сейчас, за исключением того, что $.post будет обрабатываться newComment.commentConfirm().

А теперь некоторые изменится на Comment:

// You might want to change this to use the more "modern" `class` at some point.
function Comment(comment) {
  this.description = comment.description;
  this.rating = comment.rating;
}

Comment.prototype.commentConfirm = function() {
  let doIt = confirm(`You are about to comment: "${this.description}" and give a rating of: ${this.rating} stars`);
  if(!doIt)
    return;

  let params = {
    'comment[description]': this.description,
    'comment[rating]': this.rating
  };
  $.post(whatever_the_action_is, params).success(function(response) {
    // Now render `response` directly.
  });
}

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...