I have a plugin I am writing that accepts options. It looks something like this.
$('#myObject').myPlugin({
option1: someValue
});
Where somevalue can either be a value, a control id, or a function.
I have a default settings defined like this
var settings = {
option1: null
};
Then, inside my plugin I use this to merge what the user passes in with my empty settings object
if (options) {
$.extend(settings, options);
}
This works fine when the option is a control ID or value.
My first issue is when I use a function like this
$('#myObject').myPlugin({
option1: function(){ return doStuff(); }
});
$.extend() seems to ignore the function in this case. The default value from settings is always passed into my parser. I’m also having a problem when I pass in a value instead of a control id. I parse the settings to get the value like this
function parseValue(value, defaultValue) {
if ($.isFunction(value))
return value();
if (!value)
return defaultValue ? defaultValue : '';
if ($('#' + value))
return $('#' + value).val();
return value;
};
if I pass in a date or a decimal, $('#' + value) evaluates to true.
Any ideas on how I make this work?
EDIT:
This may be wrong, but this is how I defined my plugin. It’s actually a collection of plugins
(function ($) {
//shared methods here
function parseValue(value, defaultValue) { /*...*/ }
$.fn.myplugin = function (options) {
var settings = { };
$(this).live("submit", function (event) {
//NEVER EVER EVER allow the form to submit to the server
event.preventDefault();
//logic for "posting" cross domain
});
};
$.fn.myplugin2 = function (options) {
var settings = { };
$(this).live("submit", function (event) {
//NEVER EVER EVER allow the form to submit to the server
event.preventDefault();
//logic for "posting" cross domain
});
};
})(jQuery);
The plugins hijack a form and make it submit cross domain through a jsonp get request. Each plugin submits different data to a different url, but the overall logic is the same.
I found out what I was doing wrong.
The selector test I was doing was always returning false because jquery doesn’t return undefined if nothing was found. So, I changed my parser to look like this:
and my code now looks something like this
and now all three types (value, selector, or function) can be passed in as my query options.