Im working on a private jQuery plugin in the following format:
(function( $ ){
var defaults = {};
$.fn.cmFlex = function(op开发者_运维技巧ts) {
this.each(function() {
//Element specific options
var o = $.extend({}, defaults, opts);
//Code here
});
//code Here
};
})( jQuery );
How will i go on loading the default options from the server before $.cmFlex() is first called?
$.getJSON("http://my.domain.com/prefsUrl?callback=?", function(defaults){
$.fn.cmFlex = function(opts) {
this.each(function() {
//Element specific options
var o = $.extend({}, defaults, opts);
//Code here
});
//code Here
};
});
Assuming prefsUrl returns a valid JSONP response. If you're unfamiliar with JSONP, I suggest you google it.
You have two options:
- Quick n' dirty, and 'secure' option: Make a synchronous call to the server. You can set up an ajax object to lock down the browser until it gets the answer. There's an option in jQuery's Ajax methods called
async
, which is by default set to true. If you change this to false, the JS execution flow will hang until you get the answer from the server. It's not a really good solution, because if your server is down, or the generation of those global variables is a long process, you'll have the user waiting for it. - Cleaner but 'insecure' option: in the first call to
cmFlex
, check ifdefaults
isnull
. If it is, call to the Ajax method to fill it, and put a callback function that does thecmFlex
function. The problem here is, that if it's called again before it get the default values, you'll be doing a duplicate call to the server. - Clean and secure option: put a flag in your object, something like
isLoaded
, and if the user calls tocmFlex
by second time, and this flag is set tofalse
, raise an exception, or handle it adding this call to a queue.
Good luck!
精彩评论