jQuery plugin w namespace structure
by Osman Salihovic
HTML
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<div id="div1">div 1</div>
<div id="div2">div 2</div>
<div id="click">
Click here ...
</div>
<div id="clear">
Clear Console
</div>
JavaScript
(function($) {
$.namespace = function(namespaceName, closures) {
console.log('namespace root code');
if ($.fn[namespaceName] === undefined) {
$.fn[namespaceName] = function executor(context) {
if (this instanceof executor) {
this.__context__ = context;
} else {
return new executor(this);
}
};
}
//for each functions (closureName=FN name; closure=actual fn code)
$.each(closures, function(closureName, closure) {
$.fn[namespaceName].prototype[closureName] = function() {
return closure.apply(this.__context__, arguments);
};
});
};
})(jQuery);
(function($) {
var $win = $(this); //reference to [window]
var options = {
username: 'myuser-initial',
password: 'mypass-initial'
};
/*
var defaults = {
username: '',
password: ''
},
plugin = this,
options = options || {};
*/
console.log('plugin root code');
$.namespace('alfa', {
redify: function(options) {
$(this).css('color', 'red');
console.log('redify()');
var settings = $.extend({}, {objval: 'default'}, options);
settings.that = $(this);
$(this).alfa().init(settings);
//if (typeof(params) !== 'undefined') options = params;
settings.that.val(settings.objval);
console.log('vrijednost je: ', $(this).that);
return 'some RED value';
},
init: function(settings){
settings.that.val(settings.objval);
},
greenify: function(params) {
return $(this).alfa().blueify();
},
showSettings: function() {
console.log(options);
return options;
}
});
$.namespace('alfa', {
blueify: function() {
$(this).css('color', '#0000ff');
return 'some BLUE value';
}
});
$.namespace('alfa', {
blueify2: function() {
$(this).css('color', '#0000ff');
return 'some BLUE value';
}
});
})(jQuery);
(function($) {
/*
...