I have confusion on how to proceed with my project.
I am developing an enterprise app in which lots of modules are to be written.
Most of module will be using lots of jQuery plugins to create complex grids, draw graphs for different purposes which means modules will be appending divs, tables etc a lot to DOM.
I want to preserver namespace since this will be large app.
For that I came across prototype method and self-executing anonymous function.
self-executing anonymous function seems to be recommended a lot.
My questions are
Are self executing functions reusable ?I mean these are immediately executed so lets say a module draws a complex grid for a given JSON file. So will I be able to use same self-executing anonymous function for 3 different JSON files just like a jQuery plugin ?
when there will be lots of modules written , they will all self execute on start-up. Will it effect Ram/Processor usage? Shouldn't it be way that modules should be called when needed ? what significance will self execution do ?
My Project Scope:
Kindly help me understand this self executing thing in my project scope, which is My project Holds a main namespace say "Myapp" and and its modules like Myapp.moduleA, Myapp.moduleB.MyApp will trigger its modules on click etc.
What is best way to go for me ?
Self-Executing Anonymous Func
(function( skillet, $, undefined ) {
//Private Property
var isHot = true;
//Public Property
skillet.somevar = "Bacon Strips";
//Public Method
skillet.draw = function() {
//Draw a grid
};
//Private Method
function _grid( ) {
//
}
}
}( window.skillet = window.skillet || {}, jQuery ));
You cannot reuse a self executing function, it just executes immediately and that's it.
If you need to execute it multiple times, you should just declare a function.
A possible approach is this:
var MYNAMESPACE.Object = (function(){
// private methods
var somemethod = function(){};
// public methods
return {
somepublicmethod: function(){}
};
})();
Now you can call it like this:
MYNAMESPACE.Object.somepublicmethod();
As for executing upon startup. Provided you only create methods and don't DO anything immediately inside your declaration, it won't affect performance too much unless you have a really big amount of modules. If that's the case, you should probably look into the asynchronous module loader pattern (AMD). RequireJS is a good example of that: http://requirejs.org
I wrote an article about JS namespaces which could be interesting for you:
http://www.kenneth-truyers.net/2013/04/27/javascript-namespaces-and-modules/
Related
Every function and variable that I create in KotlinJs project gets into a module. But I need to define some functions in global scope.
I use p5js library (pure js). It allows user to define event handling functions in global scope. I'm trying to use KotlinJS in this project. But I don't know how to create global functions to handle p5js's events. All my Kotlin functions are inside of the module. And to call my Kotlin code I need to specif the full name mymodule.draw()
Currently I have to make an additional layer of pure JS code with global funcs that translate execution to kotlin functions which looks like this:
function setup() {
mymodule.setup();
}
function draw() {
mymodule.draw();
}
The problem with this approach is a lot of boilerplate and repetitive code.
In case this will be useful for somebody I will leave another workaround here:
import kotlin.browser.window
fun main() {
window.asDynamic()["setup"] = ::setup
window.asDynamic()["draw"] = ::draw
}
fun setup() {}
fun draw() {}
What it actually does, it creates functions in kotlin module as usual and then assigns them to window object, which makes it global.
This solution is still not ideal, cause it needs a manual assignment for every function. At least it does it right in Kotlin project, no need to maintain a separate pure js file.
Maybe it is possible to create an annotation and leverage kotlin reflection(no idea how it's supported in KotlinJS).
Although this solution works for me, I would like to have some out of the box solution like they do for #JsNonModule external functions.
Adding on top of #Sergey's Answer, one can also use this work around when dealing with libs like p5.js
fun main() {
window.asDynamic().setup = {
// your setup code here
}
window.asDynamic().draw = {
// your draw code here
}
}
This approach minimizes the definition and the declaration of the two functions (looking at you C Language). Thanks
Unfortunately there is no way to define global function in Kotlin/JS. It is possible to use Plain module type where you have global symbols in module object which is defined in global scope.
// module M
fun foo() {}
which is accessible via M.foo
I'm asking a question:
Imagine I have a javascript module (using revealing module pattern) and I want to use it inside some prototype methods of an object. What will be the best way on your opinion to do it?
I have currently two ideas in mind:
- Pass the global module to the constructor of the object and keep it in an object property (this.myModule...)
- Use the module from the prototype method directly as global variable
Let me explain you the situation with a small example:
I have file1.js containing the module :
var myModule = (function(){
function doSomething(){...}
return {doSomething: doSomething};
})()
To use this module, which of the two options is the best for you? Or maybe you have a better option to propose?
I can't use requirejs nor any libraries to ease the modularity and dependency management of my application. Also, I can't change the existing architecture.
// Option 1
function myObject(myModule){
...
this._myModule = myModule;
}
myObject.prototype.doAnotherThing = function(){
...
this._myModule.doSomething();
}
var test = new myObject(myModule);
// Option 2
function myObject(){
...
}
myObject.prototype.doAnotherThing = function(){
...
myModule.doSomething();
}
var test = new myObject();
I'm really interested by having your point of view.
Thanks a lot in advance,
Remi
I have a Javascript function in a view which is enclosed in a closure. The closure returns a function of the same name and also has some helpers. This is the structure of the method.
this.myMethod = (function () {
function helperMethod(){
....
return true;
}
return function myMethod(args){
helperMethod();
manipulate();
}
}
My question is how do I write a Jasmine Unit Test spec to this method. How can I invoke this method ?
Using the default way of methods does not work in this case as it is anonymous.
var view = new myView();
view.myMethod();
expect ( true ).toBeTruthy();
Please help in this regard. I am a beginner to Jasmine Framework.
By closing over the helperMethod function, you've made it inaccessible to your specs so you won't be able to test it directly. You can either test it indirectly by going through the existing public interface (myMethod) or by extracting the helperMethod from the closure in some way to make it accessible publicly, this could be as a prototype method on the view, or just on this, or on a completely different helpery object altogether.
Currently I'm developing a large scale Javascript app(single page) and I've searched around the web to find some best practices. Most projects use the module pattern so the objects doesn't pollute the global namespace. At this moment I use normal objects:
function LoginModel(){
this.model = new MyModel();
this.getModel = function(){
return this.model;
};
}
This is readable and easy to maintain(my opinion). Is it better to use the module pattern just because of the namespacing or does it has other advantages I'm not aware of(counter memory leaks, ... )? Furthermore, I've already splitted up the files to have a nice MVC pattern and destroy every object when needed(counter memory leaks). So the main question is: do I need, in my case, to use the module pattern or not?
Module pattern:
var LoginModel = (function(){
var model = MyModel;
function getModel(){
return model;
};
return {
getModel: getModel
};
});
The module pattern is better for overall code organization. It lets you have data, logic and functions that are private to that scope.
In your second example getModel() is the only way to get the model from the outside. The variable declared int he module are hidden unless explicitly exposed. This can be a very handy thing.
And there's not really any drawback, other than being a little more complex. You just get more options for organization and encapsulation.
I'd use a plain object until my model gets complex enough to need more structure and some private scoping. And when you hit that point, it's trivial to redefine it as a revealing module without breaking any of the code that uses it.
If you're only going to be using one instance per page, I don't see the need to involve the new keyword. So personally I would create a revealing module like you did in your last example, and expose an object with the "public" properties.
Though I don't see your point with the getModel() function, since MyModel is obviously accessable outside of the scope.
I would have rewritten it slightly:
var LoginModel = (function(model, window, undefined){
function init(){ } // or whatever
function doSomethingWithModel(){
console.log(model);
}
return { init: init };
})(MyModel, window);
If you're uncertain of which modules that will get a model, you can use loose augumentation and change
})(MyModel, window);
to
})(MyModel || {}, window);
If you need several instances of a module, it would look something like this:
var LoginModel = (function(model, window, undefined){
function loginModel(name){ // constructor
this.name = name; // something instance specific
}
loginModel.prototype.getName = function(){
return this.name;
};
return loginModel;
})(MyModel, window);
var lm1 = new LoginModel('foo');
var lm2 = new LoginModel('bar');
console.log(lm1.getName(), lm2.getName()); // 'foo', 'bar'
There's several concepts conflated in your question
With what you call the "normal object", the function becomes a constructor function and requires the new keyword.
The second example uses the Revealing Module Pattern inside of an IIFE. This is the most popular variant of the Module Pattern, but unfortunately deeply flawed. For an explanation of the differences see my answer here, and for its flaws, see here.
Now, your question poses a false dichotomy -- normal objects or module pattern? You don't have to make a choice -- a normal object can use the module pattern simply by putting whatever it wants to keep private inside its closure scope. For example,
function LoginModel(){
var _notifyListeners = function(){
// Do your stuff here
};
this.model = new MyModel();
this.getModel = function(){
_notifyListeners();
return this.model;
};
}
This is an example of a "normal object" using the module pattern. What you have to avoid doing is what the Revealing Module Pattern does -- putting everything into closure scope. You should only put the things you want to keep private inside the closure scope.
Below is an example of a modular layout of a javascript application. I want to start using such a structure for my work. I am struggling to get my head round how it works and need to understand how to call a function that is defined in one module from a different module? Is this definitely the bet way to layout a JavaScript heavy application?
window.MainModule = (function($, win, doc, undefined) {
var modules = {};
// -- Create as many modules as you need ...
modules["alerter"] = (function(){
var someFunction = function(){ alert('I alert first'); };
return {
init: someFunction
};
}());
modules["alerter2"] = (function(){
var someFunction = function(){ alert('I alert second'); };
return {
init: someFunction
};
}());
return {
init: function(){
for (var key in modules){
modules[key].init();
}
}
};
}(jQuery, this, document));
$(window.MainModule.init);
Modularity with RequireJS:
module1.js
define( ["dependency"] , function( dep ){
return {
speak: function(){
alert( dep.message );
}
}
} );
dependency.js
define( {
message: "Hello world!"
} );
impl.js
if ( $(".someCssExpression").length ) {
require( [ "module1" ] , function( mod ){
mod.speak();
});
}
index.html
...
<script src="require.js" data-main="impl"></script>
...
Your file structure will be modular.
Your implementation will be modular.
And no clunky namespacing or weird constructs to make it feel organised.
Takes some getting used to, but totally worth it.
Also read:
ScriptJunkie article
In order to access anything it needs to be available in the scope from where you are calling. "Module" - or any capsulation method for that matter - in JS always means "function". A module is just an anonymous (unnamed) function. So to access an element defined in another function B(module) from inside function A it either has to be made available in GLOBAL SCOPE (in browsers: the window object), OR it must have obtained access some other way, e.g. by having received a reference through some function call. YUI3 ([http://developer.yahoo.com/yui/3/]) is an interesting example for the latter, there nothing of your application ever is available in global scope (I consider YUI3 one of the by far best JS frameworks for SERIOUS softwarfe development, also definitely DO check out http://developer.yahoo.com/yui/theater/, especially any videos from Douglas Crockford, a Javascript God (and I'm not usually given to giving these kinds of statements).
What you have to keep in mind with Javascript is that part of what in languages such as C is done by the compiler now happens at runtime. For such things like immediate function invocations that return a function (causing encapsulation through usage of closures) you should remember that that code runs exactly ONCE DURING LOADING, but during runtime completely different code is executed - which depends on what the on-load code execution did.
In your example the function after window.MainModule=... is executed on loading of the JS code. Note that window.MainModule does NOT POINT TO THAT FUNCTION!!!
Instead, that function is, as I said, executed on load, and the RESULT is assigned to window.MainModule. What is the result? Well, there is just one return statement, and it returns and object, and the object has just one property "init" which points to an anonymous function.
Before returning that object, though, that function creates a variable "modules" in its local scope, which points to an object. The object has two properties, and those properties are assigned functions the same way that window.MainModule is assigned one, so you have three closures all in all.
So after loading you have one global variable
window.MainModule = {
init: function(){...}
So after loading you have one global variable
window.MainModule = {
init: function(){...}
}
In the last line that function is executed.
}
In the last line that function is executed.
The example does not make a lot of sense though, because you don't really encapsulate anything. You make available the private function with double pointers: from init to the local variable someFunction, nothing is hidden. Check out the above URLs (Yahoo Developer Theater) for better examples and very thorough explanations. It is MUST-WATCH even if you never touch YUI3 - especially the videos from D. Crockford are general JS knowhow.
Well umm..
It all depands on what you need from your application.
I would suggest sticking to the jQuery plugins for as long as you touch the gui.
You could use the Namespace pattern like yahoo, and just forge a great framework for your
application.
You probably don't need your modules to run on every page, like you did when instantiating the main module (There is no point to it unless f.e. you have a widget in every page on your website).
After you finish to abstract all the actions you need from your javascript into function and modules, build a module that will load the logic according to each page/action/whatever whenever you need it.
By the way, You can always develop OO style using mootools and this is endless really. It all boils down to your application needs
I would really recommend you to watch some lectures of Douglas Crockford(As been stated before me) and here is a nice article about modules that may help you understand it a bit further. Good luck!