I'm currently writing an API that allows users to load modules (to give a kind of plugin functionality) via a loadModules() function:
Code in full:
var LC = (function(){
var alertModule = {
alertName: function(name) {
alert(name);
},
alertDate: function() {
alert(new Date().toUTCString());
}
}
var logModule = {
logName: function(name) {
console.log(name);
},
logDate: function() {
console.log(new Date().toUTCString());
}
}
return {
loadModules: function(moduleList) {
for(var i=0, l=moduleList.length; i<l; i++) {
try {
this[moduleList[i]] = eval(moduleList[i]);
} catch(e) {
throw("Module does not exist");
}
}
}
}
})();
LC.loadModules(['alertModules', 'logModule']);
The code below would add the alertModule and logModule objects to the LC object.
LC.loadModules(['alertModule', 'logModule']);
Inside the loadModules method, I'm looping through the array and using the following code to add the objects to LC:
this[moduleList[i]] = eval(moduleList[i]);
This works fine and I'm fairly sure it's secure (an error is thrown if the module doesn't exist) but is there a more elegant way of doing this? The only other way I can think to accomplish this would be to put the modules themselves inside an object so I could reference them more easily. Any other thoughts/ideas would be welcome!
Try this: http://jsfiddle.net/PUgM7/2/
Instead of referencing those "private" variables with eval() you could have a hash of modules.
var modules = {
alertModule: { .. },
logModule: { ... },
}
You could expand on this and add extra functionality like dynamically registering modules with another public method, say addModule.
return {
addModule: function(name, newModule) {
modules[name] = newModule;
},
loadModules: function() { ... }
}
Related
I have a very complex class so i decided to break into sub modules and trying to use revealing modules pattern.
I have main class and decided to divide into smaller container function. but in current scenario
But i am not able to access any internal function from outside i.e callSearchResultWithCallBack using searchFinder.Search.callSearchResultWithCallBack(). which pattern should i use to keep this code clean as well have control to call internal function in sub module.
Thanks
var searchFinder;
function SearchFinder() {
me = this;
this.searchResult = null;
this.init = function() {
declareControls();
createAccordian();
addEvents();
fillControls();
var declareControls = function() {
this.SearchButtons = jQuery('.doSearch');
this.InputLocation = jQuery('#inputLocation');
this.InputDistanceWithIn = jQuery('#inputDistanceWithIn');
this.InputName = jQuery('#inputName');
}
var addEvents = function() {
me.SearchButtons.click(function() {
me.Search();
});
}
var fillControls = function() {
var getGetCategory = function() {
}
}
}
this.Search = function() {
var url = '';
var searchCriteria = {};
validateAndCreateCriteria();
callSearchResultWithCallBack();
function validateAndCreateCriteria() {
function validateAandGetCategory() {
if (SearchValidation.ValidateZipCode(me.InputLocation.val().trim())) {
searchCriteria.location = me.InputLocation.val().trim();
} else if (SearchValidation.ValidateCityState(me.InputLocation.val().trim())) {
searchCriteria.location = me.InputLocation.val().trim();
}
}
}
// need to access it outsite
function callSearchResultWithCallBack() {
me.searchResult(searchCriteria, SearchResultCallBack);
function SearchResultCallBack() {
}
}
}
}
jQuery(function() {
searchFinder = new SearchFinder();
searchFinder.init();
searchFinder.Search.callSearchResultWithCallBack();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
This code has multiple issues, first I will address the fact that for example declareControls is not executing. First declare the function than execute!
this.init = function() {
var declareControls = function() {
this.SearchButtons = jQuery('.doSearch');
this.InputLocation = jQuery('#inputLocation');
this.InputDistanceWithIn = jQuery('#inputDistanceWithIn');
this.InputName = jQuery('#inputName');
}
var addEvents = function() {
this.SearchButtons.click(function() {
me.Search();
});
}
var fillControls = function() {
var getGetCategory = function() {
}
}
declareControls();
//createAccordian(); //not defined
addEvents();
fillControls();
}
Now let's look at others problems that will arise.
the me object referring to this is in the scope of searchFinder and does not refer to the same this in the instance of searchFinder.
function jQuery can be replaced by the commonly used $.
searchFinder.Search.callSearchResultWithCallBack() this is never going to work. Since the Search function is an object and callSearchResultWithCallBack isn't a property of this function.
Solution; make it part of the prototype of Search.
Steps:
Move callSearchResultWithCallBack outside the search function.
Add prototype to Search function
Call function via prototype.
function callSearchResultWithCallBack() {
me.searchResult(searchCriteria, SearchResultCallBack);
function SearchResultCallBack() {
}
}
this.Search.prototype.callSearchResultWithCallBack = callSearchResultWithCallBack;
If you want to fire this function outside of search use this:
searchFinder.Search.prototype.callSearchResultWithCallBack();
Please remember that callSearchResultWithCallBack will throw an error because searchCriteria is undefined.
This fixes your problems for now, but this code has to be revised thoroughly. But this should get you started. http://ejohn.org/blog/simple-javascript-inheritance/
I want to initialize my javascript class like this:
Example.init({"settings": {"baseUrl":"http://example.com"},
"user": {"id":123, "name":"john doe"} );
And then I want to be able to use it like this:
Example.settings.baseUrl
Example.user.id;
Example.user.name;
I am currently using the module pattern like this:
Example = (function(){
var _init = function(data) {
};
return {
init: function($data) {
_init($data);
}
};
})();
Example.module2 = (function(){
var _init = function(data) {
if(Example.user.id > 0) { // referencing data set in the Example.init
}
};
return {
init: function($data) {
_init($data);
}
};
})();
I'm not sure how I can expose these properties, looking for an explanation and guidance.
(please comment on best practise also, should I use $ for parameters and if so when?)
Note: Here is basic outline of what I am trying to do.
The first thing I will do is call the Example.init function in all my pages:
Example.init({"settings": {"baseUrl":"http://example.com"}, "user": {"id":123, "name":"john doe"} );
I want my other modules to be able to reference this data I set in the .init() method, see the Example.module2 I added above.
Is there a timing issue with this?
Example = (function(){
var _init = function(data){
// manually
//this.settings = data.settings || NULL;
//this.user = data.user || NULL ;
for (prop in data){
this[prop] = data[prop];
}
}
return {
init: function(data) {
_init.call(this, data);
}
};
})();
Example.init(
{"settings": {"baseUrl":"http://example.com"}, "user": {"id":123, "name":"john doe"}});
console.log(Example.settings.baseUrl);
console.log(Example.user.id);
console.log(Example.user.name);
As for your other question "using $ in variable names " - It is a comment naming convention when the variable contains a Jquery object -
This question already has an answer here:
Double-Queue Code needs to be reduced
(1 answer)
Closed 9 years ago.
Is there any way for me to shorten this code by using pointers?
I need to make a class that has mostly the same function as a given array class unshift,shift,push and pop but with different names.
var makeDeque = function()
{
var a= [], r=new Array(a);
length = r.length=0;
pushHead=function(v)
{
r.unshift(v);
}
popHead=function()
{
return r.shift();
}
pushTail=function(v)
{
r.push(v);
}
popTail=function()
{
return r.pop();
}
isEmpty=function()
{
return r.length===0;
}
return this;
};
(function() {
var dq = makeDeque();
dq.pushTail(4);
dq.pushHead(3);
dq.pushHead(2);
dq.pushHead("one");
dq.pushTail("five");
print("length " + dq.length + "last item: " + dq.popTail());
while (!dq.isEmpty())
print(dq.popHead());
})();
Output should be
length 5last item: five
one
2
3
4
Thanks!
Maybe I'm oversimplifying, but why not just add the extra methods you need to the Array prototype and call it directly?
I need to make a class that has mostly the same function as a given array class unshift,shift,push and pop but with different names.
I suppose you could add these "new" methods to Array.prototype.
Like this perhaps?
var makeDeque = (function (ap) {
var Deque = {
length: 0,
pushHead: ap.unshift,
popHead: ap.shift,
pushTail: ap.push,
popTail: ap.pop,
isEmpty: function () {
return !this.length;
}
};
return function () {
return Object.create(Deque);
};
})(Array.prototype);
DEMO
If it's still too long, you can always directly augment Array.prototype like others already mentionned. We agree that it's all experimental here and the only goal is to save characters.
!function (ap) {
ap.pushHead = ap.unshift;
ap.popHead = ap.shift;
ap.pushTail = ap.push;
ap.popTail = ap.pop;
ap.isEmpty = function () {
return !this.length;
};
}(Array.prototype);
function makeDeque() {
return [];
}
This can be compressed to 174 chars:
function makeDeque(){return[]}!function(e){e.pushHead=e.unshift;e.popHead=e.shift;e.pushTail=e.push;e.popTail=e.pop;e.isEmpty=function(){return!this.length}}(Array.prototype)
DEMO
Not sure why you need this, but my suggestions per best practice are:
Don't override the Array.prototype. The reason for this is because other libraries might try to do the same, and if you include these libraries into yours, there will be conflicts.
This code is not needed. var a= [], r=new Array(a);. You only need ...a = [];.
Ensure you are creating a real class. In your code, makeDeque is not doing what you want. It is returning this which when a function is not called with the new keyword will be the same as the window object (or undefined if you are using what is called as "strict mode"). In other words, you have made a lot of globals (which are usually a no-no, as they can conflict with other code too).
When you build a class, it is good to add to the prototype of your custom class. This is because the methods will only be built into memory one time and will be shared by all such objects.
So I would first refactor into something like this:
var makeDeque = (function() { // We don't need this wrapper in this case, as we don't have static properties, but I've kept it here since we do want to encapsulate variables in my example below this one (and sometimes you do need static properties).
function makeDeque () {
if (!(this instanceof makeDeque)) { // This block allows you to call makeDeque without using the "new" keyword (we will do it for the person using makeDeque)
return new makeDeque();
}
this.r = [];
this.length = 0;
}
makeDeque.prototype.setLength = function () {
return this.length = this.r.length;
};
makeDeque.prototype.pushHead=function(v) {
this.r.unshift(v);
this.setLength();
};
makeDeque.prototype.popHead=function() {
return this.r.shift();
this.setLength();
};
makeDeque.prototype.pushTail=function(v){
this.r.push(v);
this.setLength();
};
makeDeque.prototype.popTail=function() {
return this.r.pop();
this.setLength();
};
makeDeque.prototype.isEmpty=function() {
return this.r.length === 0;
};
return makeDeque;
}());
Now you could shorten this as follows, but I wouldn't recommend doing this, since, as it was well said by Donald Knuth, "premature optimization is the root of all evil". If you try to shorten your code, it may make it inflexible.
var makeDeque = (function() {
function makeDeque () {
if (!(this instanceof makeDeque)) {
return new makeDeque();
}
this.r = [];
this.length = 0;
}
makeDeque.prototype.setLength = function () {
return this.length = this.r.length;
};
for (var i=0, methodArray = [
['pushHead', 'unshift'], ['popHead', 'shift'], ['pushTail', 'push'], ['popTail', 'pop']
]; i < methodArray.length; i++) {
makeDeque.prototype[methodArray[i][0]] = (function (i) { // We need to make a function and immediately pass in 'i' here because otherwise, the 'i' inside this function will end up being set to the value of 'i' after it ends this loop as opposed to the 'i' which varies with each loop. This is a common "gotcha" of JavaScript
return function () {
var ret = this.r[methodArray[i][1]].apply(this.r, arguments);
this.setLength();
return ret;
};
}(i));
}
makeDeque.prototype.isEmpty=function() {
return this.r.length === 0;
};
return makeDeque;
}());
If you need to get the length by a length property, as opposed to a method like setLength() which sets it manually after each update, either of the above code samples could be shortened by avoiding the setLength() method, but you'd need to use the Object.defineProperty which does not work (or does not work fully) in older browsers like IE < 9.
I'm writing a jQuery plugin to allow the initializing of multiple, single file upload fields (using Fine Uploader) in a specified form.
Ultimately I would like the form to know that it has these single uploaders attached to it, so I can run some validations, etc before manually starting the file uploads and submitting the form.
My ideal initialization code would look like this:
var form = $("form");
form.uploader();
form.addUploader({
element: '.uploader_one'
});
form.addUploader({
element: '.uploader_two'
});
So far the plugin I wrote to make this happen looks like:
(function($) {
var Uploader = function(form){
addUploader = function() {
// Initialize Fine Uploader
}
$(form).submit(function(e) {
// Run validations, then process uploaders
$(this).submit();
}
}
$.fn.uploader = function(options) {
var uploader = new Uploader(this);
};
})(jQuery);
Most of this works, except that the addUploader function is not publicly accessible.
Might I be going about this the wrong way? Any help would be much appreciated!
You would need to make the addUploader a member of the object to make it accessible through the object (instead of as a global variable disconnected from the object):
this.addUploader = function() {
The plugin has to do something with the object so that it becomes accessible, for expample returning it:
$.fn.uploader = function(options) {
return new Uploader(this);
};
Now you can get the object from the plugin and use it:
var form = $("form");
var upl = form.uploader();
upl.addUploader({
element: '.uploader_one'
});
upl.addUploader({
element: '.uploader_two'
});
You should follow the general practice for developing plugins. A suggested structure for your plugin is something like:
(function($) {
var methods = {
init: function (options) {
var data = $(this).data("uploader-plugin");
if (!data) {
$(this).on("submit", function (e) {
});
$(this).data("uploader-plugin", new Uploader(options));
}
},
add: function (options) {
// Use `options.element`
$(this).data("uploader-plugin").elements.push(options.element);
console.log($(this).data("uploader-plugin"));
}
};
var Uploader = function (opts) {
this.whatever = opts.a;
this.elements = [];
};
$.fn.uploader = function(method) {
var args = arguments;
return this.each(function () {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(args, 1));
} else if (typeof method === "object" || !method) {
return methods.init.apply(this, args);
} else {
$.error("Method " + method + " does not exist on jQuery.uploader");
}
});
};
})(jQuery);
DEMO: http://jsfiddle.net/WyGqc/
And you will call it like this:
var form = $("form");
form.uploader({
a: "whatever";
});
form.uploader("add", {
element: ".uploader_one"
});
It actually applies it to all selected elements from the original selector, and continues chaining. It also follows the normal convention for plugin use - meaning, you call the plugin name (uploader) with different parameters to do different things.
I've confused myself nicely here. My scenario is as follows:
function DesignPad() {
function EditBar() {
...
this.removeHandler = function() {
**// how do I call Dragger.removeAsset**
}
}
function Dragger(){
...
this.removeAsset = function() {}
}
this.init = function() {
this.editBar = new EditBar();
this.dragger = new Dragger();
}
}
var dp = new DesignPad();
...
I can't seem to call Dragger.RemoveAsset. I understand the why, my question is how do I call it?
I'm trying to keep like-things separated (e.g. Dragger / EditBar) but I seem to get all sorts of mixed up in my event handlers. Any suggestions, good reading materials, etc. on this stuff?
I found Douglas Crockford's Javascript to be the best introduction to JavaScript. Especialy videos for Yahoo, like: The JavaScript Programming Language where you can learn how exactly are objects created and inherited in JS.
Solution to you problem is:
function DesignPad() {
var that = this;
function EditBar() {
this.removeHandler = function() {
print("RemoveHandler");
that.dragger.removeAsset();
}
}
function Dragger() {
this.removeAsset = function() {
print("RemoveAsset");
}
}
this.init = function() {
this.editBar = new EditBar();
this.dragger = new Dragger();
}
}
var dp = new DesignPad();
dp.init();
dp.editBar.removeHandler();
But as others noticed you could refactor some things :).
To me it just looks like you should refactor that code to make it simpler.
I think that your issue comes from the fact that a nested function is private, so you can't access it from outside.
Is an instance of Dragger a 'property' of your DesignPad object? If so, you could pass a reference to that object into your removeHandler() method.
Try this:
function DesignPad() {
function EditBar(s) {
super = s;
this.removeHandler = function() {
alert('call 1');
super.dragger.removeAsset();
}
}
function Dragger(s){
super = s;
this.removeAsset = function() {
alert('call 2');
}
}
this.init = function() {
this.editBar = new EditBar(this);
this.dragger = new Dragger(this);
}
}
var dp = new DesignPad();
dp.init()
dp.editBar.removeHandler();
alert('end');