Reputation: 1966
I'm looking for a way to set a default numerical value to my defaults parameters of my plugin or have the option to retrieve the default value via an ajax call. In other words:
var defaults = {
param1: 1000,
totalTime : null // the default value i'm looking for in seconds
}
So that:
$('.test').myPlugin({
param1: 1000,
totalTime: function () {
$.ajax({
url: 'totaltime.php',
type: 'POST',
success: function(data) {
// retrieve value here
}
});
}
});
OR
$('.test').myPlugin({
param1: 1000,
totalTime: 200 // numerical
});
I only recently started playing with plugins and found this an interesting concept but am having a little trouble with it. Here's what my plugin looks like now (the basic set up for new plugin).
(function($) {
$.fn.myPlugin = function(options) {
var plugin = this;
var defaults = {
param1: 1000,
totalTime : null
}
plugin.init = function() {
plugin.settings = $.extend({}, defaults, options);
plugin.timer();
}
plugin.settings = {}
plugin.timer = function() {
}
plugin.init();
return this;
};
})(jQuery);
Upvotes: 0
Views: 391
Reputation: 7207
just define your defaults like this:
var defaults =$.extend( {
param1: 1000,
totalTime : null
},options);
and then you can use it like defaults.param1
or defaults.totalTime
UPDATE:
the above example is how you can set the totalTime value numerically as default.
if you wanna change it during your plugin then you can do this:
defaults.totalTime=500;
or
defaults.totalTime=givenVal; //givenVal is a variable that contains the value
also in your jQuery code, you can set the totalTime as this:
$('#test').myPlugin({
totalTime:500
});
or
$('#test').myPlugin({
totalTime:givenVal
});
so now all you should do is to get the value from ajax, put it in a variable, and pass it to your plugin as mentioned above!
Upvotes: 1
Reputation: 24638
@AminJafari has indicated how to correctly define your defaults. Below is how to call your plugin with a value from an ajax request. NOTE: the totalTime callback
has to return a value, and the value has to be available to be returned. -- which means it's got to be done in the success
callback of the ajax request:
$.ajax({
url: 'totaltime.php',
type: 'POST',
success: function(data) {
$('.test').myPlugin({
param1: 1000,
totalTime: function () {
// retrieve value here
return data.timeValue; //for example
}
});
}
});
Upvotes: 0