Reputation: 2103
I'm getting into writing jQuery plugins and integrating them with AJAX. I'm cutting the fat and focusing 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 let's say I have a div and set it to use my plugin like so:
$("myDiv").myPlugin({onSave:function(value){myAjaxSaveFunction(value);});
With this setup, the plugin, save function and animation all work (assuming there is never an error). However, the myAjaxSaveFunction is asyncronous and might either return a success or failure. I currently have the save function within the plugin calling the success animation. If I had myAjaxSaveFunction return a true/false, I could (in theory), use that return value within the plugin to determine whether to run the success or failure, but not if the function is asyncronous.
So, how is this scenario typically handled? For reuse, I need to be able to customize the function that handles the data as an optional callback, but I need the plugin to wait on whether it runs the success/fail animation based on the result of the function (which might be asyncronous, or might not be).
@Kevin B: Are you suggesting this?
saveFunction:function()
{
var value = this.myInput.val();
var success = this.options.onSave(value);
if(success)
successAnimation();
else
failureAnimation();
},
wouldn't this just fall through to the if statement immediately while the this.options.onSave function is executing?
Upvotes: 4
Views: 937
Reputation: 95047
I'd suggest allowing the onSave function to be returned either a boolean value, or 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 like this:
$("myDiv").myPlugin({onSave:function(value){return myAjaxSaveFunction(value);});
function myAjaxSaveFunction(value) {
return $.ajax({...});
}
Upvotes: 3