I’ve written a plugin to supply all my popular ColdFusion defaults such as:
- returnFormat=json
- queryFormat=column
- type=’post’
- dataType=’json’
- .fail()
- .done() (but with a caught error)
It is working, but I don’t know why I have to use
myXHR = $.fn.myAjax()
instead of
myXHR = $.myAjax()
Here’s the code:
!function($) {
$.extend(
$.fn, {
myAjax: function(myURL, settings) {
var local = {};
$('#msg').empty().removeClass('alert alert-info');
local.settings = $.extend({}, $.fn.ajaxDefaults, settings);
local.myURL = myURL + '?returnFormat=json&queryFormat=column'
local.result = $.ajax(local.myURL,local.settings)
local.result.done(function(result) {
if (result.MSG) {
$('#msg').html(result.MSG).addClass('alert alert-info');
}
});
local.result.fail(function(A,B,C) {
$('#msg').html(C).addClass('alert alert-info');
});
return local.result;
},
ajaxDefaults:{
type: 'POST',
dataType: 'json',
async:false
// todo: context = this
}
}
)
$('input[type=checkbox]').bind('change', function(myEvent, ui) {
var settings = {};
settings.data = {};
settings.data.PersonID = $(this).val();
settings.context = this;
if ($(this).is(':checked')) {
settings.data.method = 'check';
myXHR = $.fn.myAjax('Evnt.cfc',settings);
myXHR.done(function(result) {
if (!result.MSG) {
log(result.QRY.DATA);
}
});
} else {
settings.data.method = 'uncheck';
myXHR = $.fn.myAjax('Evnt.cfc',settings);
myXHR.done(function(result) {
if (!result.MSG) {
log(result.QRY.DATA);
}
});
}
});
}(jQuery);
You’ve essentially set up your plugin like this:
…and therefore have a plugin that operates on jQuery objects. So this would work:
But you’re calling it like this:
Since you apparently want your function to stand alone within the jQuery namespace, you’d set it up like this:
So in the case of your code, try adding this at the bottom, right above the end of your function:
As a side note, it’s not considered good practice to add more than one namespace for your plugin (
ajaxDefaultsfrom your example). It’s worth a quick read through the jQuery Plugin Authoring page for some good tips.