Argirco Popov Argirco Popov - 22 days ago 5
Javascript Question

Break jQuery method chain with plguin function

What I want to achieve is to build a plugin that do some validation logic on an element, but I want to go on with the next chain methods, but If its not okay, to stop and abort the next chains.

For example, I have this

;(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);


So in order to continue the chain after your callback you must return this, as I did in the plugin above.

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

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


But what If I want to execute click function only if the check function logic condition was met.

Answer

You can create a plain object having property descriptor writable set to false, assign object to $._data(this[0]).events within plugin to not permit writing "events" property at element $._data() object.

;
(function($) {
  $.fn.check = function() {
    const el = this;
    // if element `.tagName` is `"DIV"` do not set events
    if (el[0].tagName === "DIV") {
      let e = Object.defineProperty(Object.prototype, "events", {
        value: null,
        writable: false
      });
      $._data(el[0]).events = e;
    }
    return el
  }
})(jQuery);
$(function() {
  $("div").check().on("click", function(e) {
      console.log(this)
    })
    .on("mouseover", function(e) {
      console.log(this)
    });
  console.log($._data($("div")[0], "events"))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div>click</div>

Comments