@jcubic
I found your snippet and tried using it, but I think it's
applying the 'singleton' data name to anything that runs it, so if I
wanted a couple of widgets to use the singleton pattern I would only
be able to create a single of those as the following would all have
the 'singleton' data name linked to the object.
However I think I found a way around it, although it isn't
completely to my liking, as I would like this function to be used
within the widget's '_create' method, making sure nobody without
coding knowledge would be the wisest and try to declare extra widgets
of the same type, where conflicts might arise by doing so.
So here's what I got so far and a
JSBIN:
- console.log('-----START-----');
-
- $.widget('att.att_overlay', {
-
_create: function() {
- console.log('made widget');
-
},
- test: function(text) {
- console.log('Passing
stuff into widget -> ' + text);
- }
- });
-
- (function($) {
-
$.fn.singleton = function(widgetName) {
-
if
($('body').data(widgetName)) {
-
return $('body').data(widgetName);
-
}
- switch(widgetName) {
- case ('att_overlay'):
$(this).att_overlay(); break;
- default:
console.log('Widget isn\'t configured to run as a singleton.'); break;
- }
-
$('body').data(widgetName, this);
-
return this;
-
};
- })(jQuery);
-
- /* ######## USAGE ######## */
- var overlay = $('<div></div>').singleton('att_overlay');
-
- var foo = $('<div></div>').singleton('att_overlay');
-
- //passing stuff into overlay widget
- overlay.att_overlay('test', 'hello world!');
-
- console.log($('body').data());
-
console.log('overlay === foo
-> ' + (overlay === foo));
My intention would be to declare the 'att_overlay' widget as any
other like this:
-
$('<div></div>').att_overlay();
but have the singleton pattern applied within the widget to keep
it hidden from the widget call.
Do you have any tips? Trying to run the 'singleton()' function
within the '_create' method of the widget wasn't working and I assume
it has to do with the data name already existing, I think it needs to
run the singleton function before running the widget instantiation,
although I would prefer it the other way round, as I've mentioned.
Thanks in advance,
Fernando Silva