Global object with functions to be overriden by each project JS? - javascript

I'm wondering how I should design my javascript files.
I will have a global.js file which will be used for all projects. Then each project will have it's own project.js file, containing specific functions/overrides/settings just for that project.
So I'll want to write all my "global" functions in the global.js file:
Global = function() {
var config = {'alpha': 1};
function getConfig() {
return this.config;
}
function printConfig() {
console.log(this.getConfig());
}
};
Global.prototype.echoConfig = function() {
console.log(this.getConfig());
};
and I guess my project.js file, would look like:
var project = new Global();
Global.prototype.projFunc = function() { return 2; };
However, I haven't figured out how to get the config from global.js ?
I'm using jQuery, and have noted there's the $.extend function that looks nice, however I'd like to first set-up the structure for my global.js and project.js - in general I'd probably want to move most functions from project.js into global.js, but there might be one or two projects that only need 1 specific function for that application.

you need to have getConfig in a public scope, and since you have config declared in a "private" way, you cannot use this.config to get the config, just use config.
Global = function() {
var config = {'alpha': 1};
this.getConfig = function() {
return config;
}
function printConfig() {
console.log(this.getConfig());
}
};
Scope Tutorial

Related

How can I make my JavaScript library global?

I want to create a JavaScript library and have it readily available everywhere, exactly as Moment.js does.
For example, when I import Moment.js I can use it wherever I want by just typing:
moment.someMomentFunction()
Similarly, I'd want to call my function from everywhere by just doing:
mylib.function1()
mylib.function2()
etc..
Looking at the Moment.js source code I cannot see any reference to the window object (which is the one you should use if you want your object to be global)
EDIT: If you specifically want to create a library, export / import should help you:
import * as myModule from '/modules/my-module.js';
Export a function in the library with the export keyword:
export function bing(Parameters here) {
alert("bong");
}
As answered in Calling a javascript function in another js file
You can only call functions from files that were loaded before and are in the same scope. If the accepted answer from the refered post doesn't work, try jQuery
$.getScript(url, function() {
bläh();
});
Ordinary I use something like this to define a separate module using ES5.
LibName= window.LibName || {};
LibName = function () {
var yourVar1;
var yourVar2;
publicFunc1 = function() {
};
privateFunc2 = function() {
};
return {
"publicFuncName" : publicFunc1
}
}();
With the help of ES6, you may create with class and without window variable.
class MyLib {
constructor() {
this.foo = 1;
this.bar = 2;
}
myPublicMethod1() {
return this.foo;
}
myPublicMethod2(foo) {
return foo + this.bar;
}
}
const instance = new MyLib();
export { instance as MyLib };
In code, you going to use it like this
import { MyLib } from './MyLib';

Accessing global method with namespace in TypeScript

I'm trying to call a method in another .js file that looks like this:
if (typeof Shared === "undefined" || !Shared) {
var Shared = {};
}
Shared.HelperClass = (function ()
{
// ... private stuff here
return {
Init: function()
{
},
TestMethod: function(name)
{
return name;
}
};
})();
Naturally to call init in Javascript, i'd call:
Shared.HelperClass.Init();
Now I have a TypeScript file i'd like to call this in, but it throws a compiler error because it doesn't know what it is.
How do I tell TypeScript about these methods such that I can call this code from my .ts file?
How do I tell TypeScript about these methods such that I can call this code from my .ts file?
Create a file globals.d.ts and add the following
declare var Shared:any;
Done!
More
More on migrating : https://basarat.gitbooks.io/typescript/docs/types/migrating.html

extending a module when module is using "module.exports"

I've read a few pages on extending a module.They revolve around using a functional form of a module and I get how to do it (from https://toddmotto.com/mastering-the-module-pattern/)
var Module = (function () {
return {
publicMethod: function () {
// code
}
};
})();
but what I have is two modules like this
util.js
module.exports = {
thing1: function() {// do thing1 stuff }
}
extend.js a package I can't change (from npm)
module.exports = {
thing2: function() {// do thing2 one stuff}
}
now pretending I am going to use my util.js module
const _ = require('util.js);
let catin = _.thing1; // that's easy
let thehat = _.thing2;. // this was util.js extended.
I could in util.js just do this.
const ex = require('extend.js')
module.exports = {
thing1: function() {// do thing1 stuff }
thing2: ex.thing2
}
and that's ok since extend.js only has one function/method to extend, but I would like to extend this into my util library https://github.com/dodekeract/bitwise/blob/master/index.js but it has 22! items to extend.
There must be a better slicker way yes?
I'm open to refactoring my util.js file (but not hand coding each extension like I showed) so it extends automatically but obviously can't refactor that package I'm not maintaining, short of a fork...ugh. Also not interested in adding a sub deal like
ex: ex
_.ex.thing2
Ideas?
So given Molda's hint I'll share what I put together to make this question more useful for others. I put together a simple way of building a (utility) module from a folder of (utility) modules plus other one off packages (e.g. bitwise)
Make a utils.js module in say lib/ with this (you'll need require-all or some such package)
let utils = require('require-all')(__dirname + '/util');
let bw = require('bitwise');
let self = module.exports = (function(){
let util={};
for (var key in utils) {
util = utils.object.merge_keys(util,utils[key])
}
util = utils.object.merge_keys(util,bw)
return util;
}());
now make a subdirectory lib/util/ and fill it with your utility modules. Have one of those modules contain this key/function
merge_keys: function (obj1,obj2){
var obj3 = {};
for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
return obj3;
}
and be sure that module name matches the key used in this line util = utils.object.merge_keys(util,utils[key]). In my case I have a module object.js in lib/util/ containing merge_keys
Then just require the utils.js module and all will be as one including access to the merge_keys function for other merging :-).
let _ = require('./lib/utils');
// see if it worked
console.log(_);
beware: there is no checking for duplicate key names between modules
notes:
let self= allows one to refer to any other key within the merged object itself like self.myfunctionkeyname( )

protractor calling an exported function within the same module

I'm newer to using Protractor for automation, so forgive me if this ends up being a dumb question. I have a helper.js module with a bunch of functions that I or other team members can use. One of the functions from helper.js needs to call to one of the existing functions in the module.
Is this possible? I have tried several different ways to do this and so far none have worked other than to break the helper functions into a separate js file that I need to call to.
Example:
helper.js:
module.exports = {
newbrowsertab: function(){
<code>
},
anotherfunction: function(){
<code>
<call to newbrowsertab();>
<code>
},
anotherfunction2: function(){
<code>
}
};
In the call to the newbrowsertab function, I've tried:
module.newbrowsertab();
this.newbrowsertab();
self.newbrowsertab();
You could use Prototypal inheritance then:
// helper.js functions
// create object
var Util = function() {};
// extend object
Util.prototype.enterPassword = function() {
// code
};
// extend object
Util.prototype.clickLogin = function() {
// code
};
// use `this` to call functions in same module
Util.prototype.fullLogin = function() { // extend object
this.enterPassword();
this.clickLogin();
};
module.exports = new Util();
Then in your test file:
var Util = require('./path/to/helper.js);
Util.fullLogin();
etc...
Expanding on the prototypal convention.
Any functions that are only helpers for other exported functions could be named with an underscore and declared to be executed later.
function _helperFunction(){
// do something
// return something
}
var exposedFunction = function() {
// do something
var x = _helperFunction();
// Do something else
}
module.exports = {
exposedFunction : exposedFunction
};

Execute NodeJS module with specific variables injected

I have a module like below
'use strict';
var val = GlobalVariable.someMethod();
...
...
module.exports = myExportedClass;
I am calling it with require('./myModule');. But would like to know if GlobalVariable can be dynamically injected.
I have tried this method, though I know that this does not work :)
(function(GlobalVariable) {
require('./myModule');
})(SomeOtherGlobalVariable);
So it did not, because module will execute in different scope. Is there any other way where I can pass my own version of GlobalVariable when using require.
Yes, it can be injected. Do something like the following:
module.exports = function(injectedObject) {
return {
doSomething: function() {
return injectedObject.something();
}
}
};
you can pass you variable as an argument when requiring it
yourvariable="value";
var file = require('./myModule')(yourvariable);
or can pass it separately, as file now contain function reference of module.exports
yourvariable="value";
var file = require('./myModule');
file(yourvariable)
your module will look like as:
module.exports = function(yourVaraible) {
yourVaraible.myfunction = function() {
};
return yourvariable;
};

Categories

Resources