JQuery plugin: call a callback method which can then call plugin functions based on the response

I am going to write jQuery plugins and integrate them with AJAX. I reduce fat and focus on the basics:

(function($) { function MyPlugin(el, options) { this.element = $(el); this.myInput = false; this.options = $.extend( { onSave:function(){} }, options); this.initialize(); } $.fn.myPlugin = function(options) { var control = new MyPlugin(this.get(0), options); return control; }; MyPlugin.prototype = { initialize:function() { var me = this; //specifics shouldn't really matter //it creates some HTML to go inside the element //within that HTML is an input, which I can successfully invoke keyup: me.myInput.keyup(function(event) { if(keyPressIsEnter(event) me.saveFunction(); }); }, saveFunction:function() { var value = this.myInput.val(); this.options.onSave(value); //CURRENTLY I CALL SUCCESS ANIMATION successAnimation(); }, successAnimation:function() { //do something to the markup within element for success }, failureAnimation:function() { //do something to the markup within element for failure } }; })(jQuery); 

and say that I have a div and set it to use my plugin as follows:

 $("myDiv").myPlugin({onSave:function(value){myAjaxSaveFunction(value);}); 

With this setting, the plug-in, the save function and the animation work (provided that there will never be errors). However, myAjaxSaveFunction is asynchronous and can either return success or failure. I currently have a save function inside the plugin causing an animation of success. If myAjaxSaveFunction returned true / false, I could (theoretically) use this return value in the plugin to determine whether success or failure should be triggered, but not if the function is asynchronous.

So, how is this script usually handled? For reuse, I need to set up a function that processes the data as an additional callback, but I need a plugin to wait if it will run the animation with success / failure, based on the result of the function (which may or may not be asynchronous) .

@Kevin B: Do you offer this?

 saveFunction:function() { var value = this.myInput.val(); var success = this.options.onSave(value); if(success) successAnimation(); else failureAnimation(); }, 

wouldn't it just be executed in the if statement right away while this.options.onSave function is being executed?

+4
source share
1 answer

I suggest that the onSave function return both a boolean and a promise object.

 saveFunction:function() { var value = this.myInput.val(); var success = this.options.onSave(value); if(success && success.promise) success.promise().done(successAnimation).fail(failureAnimation); elseif (success) successAnimation(); else failureAnimation(); }, 

Now you can use it as follows:

 $("myDiv").myPlugin({onSave:function(value){return myAjaxSaveFunction(value);}); function myAjaxSaveFunction(value) { return $.ajax({...}); } 
+3
source

All Articles