【问题标题】:Custom rails confirm box (with $.rails.confirm override)自定义 rails 确认框(带有 $.rails.confirm 覆盖)
【发布时间】:2011-11-18 03:34:49
【问题描述】:

我一直在修补这个问题很长时间。

我想用我自己滚动的东西劫持默认的 JS 确认对话框。我想使用完全自定义的布局(引导程序(来自 twitter)对话框面板)。

我所拥有的不起作用。它显示得很好,我可以单击按钮,它会消失。文档说你应该在 Ok 的情况下返回 true,在 Cancel 的情况下返回 false。这很可爱,但它不起作用。看起来我需要一个回调或对最初调用该函数的对象的引用。甚至后者也是不可能的,因为 $.rails.confirm 只传递消息。

this 问题的第一个答案非常有趣。我需要一种方法使其成为模态,以便等待自定义对话框的返回。)

那么有人可以指点我正确的方向吗?我感觉我要拍东西了。难的!! jQuery UI 只是一个选项,我可以让我的对话框看起来和我现在的完全一样。

这是我所拥有的:

这是放在我的application.erb中

<div id="modal-confirm" class="modal">
  <div class="modal-header">
    <h3>Are you sure?</h3>
    <a href="#" class="close">×</a>
  </div>
  <div class="modal-body">
    <p>{{VALUE}}</p>
  </div>
  <div class="modal-footer">
    <a id="modal-accept" href="#" class="btn primary">OK</a>
    <a id="modal-cancel" href="#" class="btn secondary">Cancel</a>
  </div>
</div>

javascript.js:

function bootStrapConfirmDialog(message) {
  // get a handle on the modal div (that's already present in the layout).
  d = $("#modal-confirm");
  // replace the message in the dialog with the current message variable.
  $("#modal-confirm div.modal-body p").html(message);
  // offset the dialog so it's nice and centered. we like that ;)
  // d.offset({ top: 400, left: (document.width - d.width) / 2 });
  d.center();

  // show the dialog.
  d.toggle(true);
  console.log("popped open");
}

$(document).ready(function(){
  // jquery support
  $.fn.extend({
    center: function () {
      return this.each(function() {
        var top = ($(window).height() - $(this).outerHeight()) / 2;
        var left = ($(window).width() - $(this).outerWidth()) / 2;
        $(this).css({position:'absolute', margin:0, top: (top > 0 ? top : 0)+'px', left: (left > 0 ? left : 0)+'px'});
      });
    }
  });

  // modal stuff
  $("#modal-confirm").toggle(false);

  // wire up cancel and x button.
  $("#modal-confirm #modal-cancel, #modal-confirm a.close").click(function (e) {
    d.toggle(false);
    console.log("clicked cancel");
    return false;
  });

  // wire up OK button.
  $("#modal-confirm #modal-accept").click(function (e) {
    d.toggle(false);
    console.log("clicked accept");
    return true;
  });

  // wire up our own custom confirm dialog.
  $.rails.confirm = function(message) { console.log("start intercept"); return bootStrapConfirmDialog(message); };
});

最后在我看来:

<%= link_to 'delete customer', customer_path(@customer), :class => 'btn danger', :method => :delete, :confirm => "Are you sure you would like to delete '#{@customer.name}'?" %>

@ 格林威治标准时间 23:46

好吧,我想出了一个办法……但它并不漂亮。我基本上以将实际元素传递给 $.rails.confirm 方法的方式扩展了 jquery-rjs。这样我至少知道如果在模态中按下 OK 按钮会发生什么。所以这是新的时髦代码。

我的新 application.js。奇迹般有效。但是我对我必须覆盖多少东西感到有点不安。我可能弄坏了一些东西,我什至不知道它(rails.formSubmitSelector 和/或 rails.formInputClickSelector)。因此,如果您有更好的解决方案... give :D thx!

function bootStrapConfirmModal(message, element) {
  // get a handle on the modal div (that's already present in the layout).
  d = $("#modal-confirm");
  // replace the message in the dialog with the current message variable.
  $("#modal-confirm div.modal-body p").html(message);
  // offset the dialog so it's nice and centered. we like that ;)
  d.center();

  // wire up cancel and x button.
  $("#modal-confirm #modal-cancel, #modal-confirm a.close").click(function (e) {
    d.toggle(false);
    return false;
  });

  // wire up OK button.
  $("#modal-confirm #modal-accept").click(function (e) {
    d.toggle(false);

    // actually handle the element. This has to happen here since it isn't an *actual* modal dialog.
    // It uses the element to continue proper execution.
    $.rails.handleLink(element);

    return false;
  });

  // show the dialog.
  d.toggle(true);
};

$(document).ready(function(){
  // jquery support
  $.fn.extend({
    center: function () {
      return this.each(function() {
        var top = ($(window).height() - $(this).outerHeight()) / 2;
        var left = ($(window).width() - $(this).outerWidth()) / 2;
        $(this).css({position:'absolute', margin:0, top: (top > 0 ? top : 0)+'px', left: (left > 0 ? left : 0)+'px'});
      });
    }
  });

  // modal stuff
  $("#modal-confirm").toggle(false);



  // $.rails overrides.

  // wire up our own custom confirm dialog. Also extend the function to take an element.
  $.rails.confirm = function(message, element) { return bootStrapConfirmModal(message, element); };

  $.rails.allowAction = function(element) {
    var message = element.data('confirm'),
        answer = false, callback;
    if (!message) { return true; }

    if ($.rails.fire(element, 'confirm')) {
      // le extension.
      answer = $.rails.confirm(message, element);
      callback = $.rails.fire(element, 'confirm:complete', [answer]);
    }
    return answer && callback;
  };

  $.rails.handleLink = function(link) {
    if (link.data('remote') !== undefined) {
      $.rails.handleRemote(link);
    } else if (link.data('method')) {
      $.rails.handleMethod(link);
    }
    return false;
  };

});

【问题讨论】:

    标签: javascript jquery ruby-on-rails


    【解决方案1】:

    这是在 Rails 中更改确认框的工作演示:http://rors.org/demos/custom-confirm-in-rails

    提供了 Boostrap、jQueryUI 和 Noty 的示例。

    【解决方案2】:

    我为 Rails 3.1 编写了一个示例,以使用此解决方案更改警报,但不是用引导程序替换本机警报,而是执行以下操作:

    • 将链接/按钮文本更改为“确定?” 2 秒
    • 如果在 2 秒内点击了链接/按钮,则执行该操作
    • 否则链接/按钮会翻转回旧文本并且什么都不会发生。

    这里有一个要点:https://gist.github.com/2594409

    这是在 UX 论坛中的讨论之后:

    https://ux.stackexchange.com/questions/20741/action-confirmation-through-double-clicking

    【讨论】:

      【解决方案3】:

      有这个功能的拉取请求似乎工作正常 https://github.com/rails/jquery-ujs/pull/196

      【讨论】:

        【解决方案4】:

        我发布我的工作解决方案以防它对任何人有帮助。当单击通过以下选择器匹配的链接或按钮时,此解决方案会呈现引导模式:

        $('a.ajaxLink, button.ajaxButton')

        HAML 代码

        - genericConfirmationModalId = "genericConfirmationModal"
        .modal.fade{:role => "dialog", :tabindex => "-1", id: genericConfirmationModalId }
          .modal-dialog{:role => "document"}
            .modal-content
              .modal-body
                %button.close{"aria-label" => "Close", "data-dismiss" => "modal", :type => "button"}
                  %span{"aria-hidden" => "true"} ×
        
                %h3.text-center<
                  Are you sure?
        
              .modal-footer
                .row<
                  .col-md-6<
                    = button_tag(type: 'button', class: "btn btn-primary btn-lg genericConfirmationModalNoBtn" ) { "No" }
                  .col-md-6<
                    = button_tag(type: 'button', class: "btn btn-danger btn-lg genericConfirmationModalYesBtn") { "Yes" }
        

        JS 代码

        (function ($) {
          // ================ STARTS - CUSTOM rails_ujs CONFIRMATION DIALOG RELATED JS
        
          blockUI = function() {
            $.blockUI();
          };
        
          unblockUI = function() {
            $.unblockUI();
          };    
        
          // Reference: http://thelazylog.com/custom-dialog-for-data-confirm-in-rails/
          $.rails.confirmed = function(element) {
            hideGenericConfirmationModal();
            element.attr('data-confirmation-answer', '1');
            element.trigger('click.rails');
          }
        
          // Overridden version
          // Reference: https://github.com/rails/jquery-ujs/blob/master/src/rails.js#L88
          $.rails.allowAction = function(element) {
            var message = element.data('confirm'),
                answer = false, callback;
            if (!message) { return true; }
        
            var executeCustomBehavior = !!element.attr('data-confirmation-answer');
        
            if (executeCustomBehavior) {
              answer = element.attr('data-confirmation-answer') == '1' ? true : false;
              callback = $.rails.fire(element, 'confirm:complete', [answer]);
            } else {
              if ($.rails.fire(element, 'confirm')) {
                try {
                  answer = $.rails.confirm(message);
                } catch (e) {
                  (console.error || console.log).call(console, e.stack || e);
                }
                callback = $.rails.fire(element, 'confirm:complete', [answer]);
              }
            }
        
            return answer && callback;
          };
        
          bindblockUIOnAjaxLinks = function() {
            $('a.ajaxLink, button.ajaxButton').off('click').on('click', function() {
              var linkTriggersConfirmationDialog = !!$(this).attr('data-confirm');
        
              if (linkTriggersConfirmationDialog) {
                // Reference: http://stackoverflow.com/questions/19516654/rails-ujs-confirm-box-cancel-button-callback
                $(this).on('confirm:complete', function(e, response) {
                  if(response) {
                    blockUI(); // Block and Unblock UI was applicable in my case. It is not necessary to use this solution.
                  } else {
                    unblockUI();
                  }
                });
        
                bindShowEventOnGenericConfirmationModal($(this));
                showGenericConfirmationModal();
                return false;
        
              } else {
                blockUI();
              }
            });
          };
        
          isGenericConfirmationModalAnswerYes = function() {
            return genericConfirmationModalAnswerHiddenField().val() == '1';
          };
        
          genericConfirmationModal = function() {
            return $("#genericConfirmationModal");
          };
        
          genericConfirmationModalYesBtn = function() {
            return genericConfirmationModal().find('.genericConfirmationModalYesBtn');
          };
        
          bindClickEventOnGenericConfirmationYesBtn = function(elementTriggeredConfirmation) {
            genericConfirmationModalYesBtn().off("click").on("click", function(event) {
              // console.log("generic confirmation modal yes button event callback");
              $.rails.confirmed(elementTriggeredConfirmation);
            });
          };
        
          genericConfirmationModalNoBtn = function() {
            return genericConfirmationModal().find('.genericConfirmationModalNoBtn');
          };
        
          bindClickEventOnGenericConfirmationNoBtn = function() {
            genericConfirmationModalNoBtn().off("click").on("click", function(event) {
              //    console.log("generic confirmation modal no button event callback");
              hideGenericConfirmationModal();
              unblockUI();
            });
          };
        
          showGenericConfirmationModal = function() {
            genericConfirmationModal().modal('show');
          };
        
          bindShowEventOnGenericConfirmationModal = function(elementTriggeredConfirmation) {
            genericConfirmationModal().off('shown.bs.modal').on('shown.bs.modal', function (event) {
              // console.log("generic confirmation modal shown event callback");
              bindHideEventOnGenericConfirmationModal();
              bindClickEventOnGenericConfirmationYesBtn(elementTriggeredConfirmation);
              bindClickEventOnGenericConfirmationNoBtn();
            })
          };
        
          hideGenericConfirmationModal = function() {
            genericConfirmationModal().modal('hide');
          };
        
          bindHideEventOnGenericConfirmationModal = function() {
            genericConfirmationModal().off('hidden.bs.modal').on('hidden.bs.modal', function (event) {
              // console.log("generic confirmation modal hidden event callback");
              // Nothing to handle as of now
            })
          };
        
          // ================ ENDS - CUSTOM rails_ujs CONFIRMATION DIALOG RELATED JS
        
        }) (jQuery);
        
        var ready;
        
        ready = function() {
          bindblockUIOnAjaxLinks();
        };
        
        // References:
        //  http://stackoverflow.com/questions/18769109/rails-4-turbo-link-prevents-jquery-scripts-from-working
        //  http://stackoverflow.com/questions/18770517/rails-4-how-to-use-document-ready-with-turbo-links
        $(document).ready(ready);
        $(document).on('page:load', ready);
        

        【讨论】:

        • TypeError: $.blockUI 不是函数
        • @JosephK 很抱歉听到这个消息。 blockUIunblockUI 这些函数在内部使用 jQuery BlockUI 插件。它可在malsup.com/jquery/block 获得。不需要包含该插件,但如果包含它,代码应该开始工作。基本上,这些函数用于显示和隐藏 Ajax 请求进行中指示器。希望有帮助。谢谢。
        • 好的 - 将在未来的项目中尝试。我最终只是手动完成了所有操作:当他们单击自定义框上的“提交”时,我发现了,手动隐藏该框,删除链接的“确认”属性,然后 vanilla-javascript “单击”链接(由于 jQuery 在链接上的点击功能存在一些奇怪的问题)。
        • $.rails 未定义。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-27
        • 1970-01-01
        • 2013-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多