使用插件函数打破 jQuery 方法链

Break jQuery method chain with plguin function

我想要实现的是构建一个插件,对元素执行一些验证逻辑,但我想继续使用下一个链方法,但如果它不行,停止并中止下一个链。

比如我有这个

;(function($, window, document, undefined) {
  var pluginName = 'check';

  $.fn[pluginName] = function(options) {
    return this.each(function() {
      if (!$.data(this, 'plugin_' + pluginName)) {
        $.data(this, 'plugin_' + pluginName, new Plugin(this, options));
      }
    });
  }

  function Plugin(element, options) {
    // Do the logic here
  }
})(jQuery, window, document);

因此,为了在回调后继续链,您必须 return this,就像我在上面的插件中所做的那样。

jQuery( document ).ready( function($) {

button.check().on( 'click', function(){
    // do something
});});

但是如果我想仅在满足 check 功能逻辑条件时才执行 click 功能。

您可以使用 Object.freeze() 创建一个普通对象来防止对象的属性被更改;在插件中将对象分配给 $._data(this[0]).events 以不允许在元素 $._data() 对象处写入 "events" 属性。

;
(function($) {
  $.fn.check = function(type, conditions) {
    const el = this;
    let condition = conditions || el[0].tagName === "DIV";
    // if element `.tagName` is `"DIV"` do not set events
    if (condition && !type) {
      if (!$._data(el[0])["events"]) {
        let e = Object.defineProperty(new Object(), "events", {
          value: null
        });
        Object.freeze(e);
        $._data(el[0]).events = e

        return el
      }
    }
    if (type && type === "bool") {
      return condition
    }
    if (type && type === "delete") {
      $._data(el[0]).events = null;
      return this
    }
  }
})(jQuery);
$(function() {
  console.log("check called, do not attach events, try clicking DIV");
  $("div").check().on("click", function(e) {
      console.log(this)
    })
    .on("mouseover", function(e) {
      console.log(this)
    });
  // boolean 
  console.log("check boolean:", $("div").check("bool"));
  console.log("allow events in ten seconds");
  setTimeout(function() {
  // delete 
  console.log("check delete:", $("div").check("delete")[0].tagName);
  console.log("click DIV");
  $("div").on("click", function(e) {
     console.log(this)
  });
  }, 10000)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div>click</div>