I have an app that has a number ajax requests and instead of writing them all out, I created a plugin that takes options based on the request I am making.
I would like the ajax requests to occur when page loads and when the user clicks, mouses over certain buttons.
I decided to use the jquery.bind() method to bind the ajax request to what event takes place. But I am running into a problem when the event is 'load' and the jquery selector is $('window') or document.
Currently, I put a conditional statement to make it work, but then I have write the same function twice just for the 'load' event like this:
(function($) {
$.fn.getData = function(options) {
var defaults = {
eventType : "load",
// more default options
}
var options = $.extend(defaults, options);
if (options.eventType == "load")
{
$.ajax({
// ajax object with options
});
}
else {
return this.bind(options.eventType, function() {
$.ajax({
// ajax object with options
});
return false;
});
}
}
})(jQuery);
So when on my view pages, I call the plugins like this:
// for click events
$('#selector').getData({
eventType : 'click',
// other default options
});
// need ajax when page loads
$('window').getData({
eventType : 'load',
// other default options
});
I don't know if there is anyway around writing the function twice and I'm also unsure that it's even good practice to bind event handler to the Window's page load event, but not sure else how to make this plugin flexible to work with browser events like page load and user events like click, mouseover.
Any help would be greatly appreciated. Thanks