Trying to make a plugin for jquery. Here is its most simplified version:

(function($) { $.extend({ VK: function(options) { this.init = function() { } this.init(); // allow jQuery chaining return this; } }); })(jQuery); 

At the moment my plugin is being called in the following way:

 $.VK(); 

I want to create an event handler in the style as implemented, for example, for ajax:

 $.VK().done(function( data ) { }).fail(function( data ){ }); 

How can this be implemented? That is, the question is how to call the done () function from the plugin?

I think you need something like this, but it certainly does not work
Jsfiddle

 (function($) { $.extend({ VK: function(options) { this.init = function() { var someCondition = true; if (someCondition) { this.done("OK") } else { this.fail("fail") } } this.init(); // allow jQuery chaining return this; } }); })(jQuery); 
  • done and fail are methods of a Promise or similar jQuery object. Therefore, to use them, the VK function must return a promise or an object in which there are these functions - Grundy
  • in your code, $.VK() returns a global jQuery object to which you also add the init method. - Igor
  • @Igor, And what should $ .VK () return? I just never did jquery plugins - koks_rs
  • var result = {init: function(){...}, done: function(){...; return this; } fail: function(){...; return this;} }; return result; And callbacks in the code are not yet visible. - Igor
  • and how is your plugin associated with jQuery? why not just make a separate module? - Mikhail Vaysman

1 answer 1

In general, thanks to your tips so far it turned out like this:

 (function($) { $.extend({ VK: function(options) { init = function() { var deferred = $.Deferred(); var someCondition = true; if (someCondition) { deferred.resolve("ok"); } else { deferred.reject("fail"); } return deferred.promise(); } return init(); } }); })(jQuery); $(function() { $("#button").click(function() { $.VK().done(function(data) { alert(data); }); }); }); 
  • why this. before init ? - Igor
  • @Igor, corrected, thanks. - koks_rs
  • then add a var before it - Grundy