How to set/redefine variable in external js file - javascript

How can I re-define variable in external js file 'js/sample.js'?
The main idea was not touch core file and be possible to pass a new value (to var COUNT_DEFAULT) on js load from my new module.
core js example:
(function(_, $) {
var COUNT_DEFAULT = 2;
...

Not sure if I understood you well, but you can do it like that.
var module = (function (myVal) {
var COUNT_DEFAULT = myVal || 2;
return {
val: COUNT_DEFAULT
};
});
var defaultVal = module();
var customVal = module(45);
console.log(defaultVal);
console.log(customVal);

Related

Receive data from Nodejs Module.Exports

I have created a node module
Module file :
var functions = {};
functions.test = function(){
console.log("Invoked");
return "Hello";
}
module.exports = functions;
Main File :
const FUNCTIONS = require('./modulefile');
var x = FUNCTIONS.test();
console.log(x);
Now, here I can see "Invoked" means function is getting executed.
But x is undefined, seems value is not getting returned.
How can I return value from test() to main file.
You could use callbacks?
Hard to say what the underlying problem is considering people have got your code working.
Model file:
var functions = {
test: function(callback) {
console.log("Invoked");
callback("Hello")
}
}
module.exports = functions;
Other file:
var Functions= require('./functions');
var x
Functions.test(function (result) { x = result });
console.log(x);
Your code works just fine, I replicated it and it works
check it out here https://repl.it/#Muhand1/module-export

How can I pass variables to external javascript file that can be accessed by all the functions

I have a Kendo grid whose Events property is hooked to a function(Grid_OnRowSelect) in external javascript file. There are other functions in the external javascript file ( like on button click * $("#btnS").on('click', function () {....* ) and few others. The Grid_OnRowSelect function and the other functions use common set of variables. How can I pass variables to an external javascript file from a view (cshtml) that can be accessed by all the functions.
#(Html.Kendo().Grid<MyModel>()
.Name("rGrid")
.Events(events => events.Change("Grid_OnRowSelect"))
.Columns(columns =>
{
columns.Command(command =>
.......
.......
.......
The external js file is
var MYFunc = MYFunc || (function () {
var _args = {}; // private
return {
init: function (Args) {
_args = Args;
// some other initialising
},
helloWorld: function () {
alert('Hello World! -' + _args[0]);
},
Grid_OnRowSelect: function (e) {
var data = this.dataItem(this.select());
detailRequestID = data.ID;
var url = _args[1] + "/" + detailRequestID;
window.location.href = url;
},
onError: function (e, status) {
//alert("A server error has occurred!");
var url = _args[2];
window.location.href = url;
}
};
}());
How I'm trying to pass arguments
<script>
window.onload = function(){
var searchUrl = #Url.Action("Search");
var updateUrl = #Url.Action("Update");
var errorUrl = #Url.Action("ServerError", "Error");
};
MYFunc.init([searchUrl, updateUrl, errorUrl]);</script><script src="~/Scripts/Index.js"></script>
But when Grid_OnRowSelect or any of the functions gets executed _args is undefined. What is not correct?
Thanks.
If you just declare a variable outside of a function in javascript it will be available to all code JS code that is loaded AFTER it. The fact that the file is external does not matter, just that it loads into the DOM after the place where you set your global variables.
Example
var globalVar = "I am global";
function test(){
var copy = globalVar;//copy now == "I am global"
var nonglobalVar = "I am not";//this is local to the function
}
var global2 = globalVar;//global2 now == "I am global"
var anotherVar = nonglobalVar;//this line will throw an error because variable is out of scope.
Another common tactic is to write your values to a hidden field in the html and then access that from your external functions.

How to have multiple imports under a same variable

I want to organize my project imports with browserify so that I have a global utils variable from which I can call and execute functions much like jquery's $.
So in the end I want something like:
window.utils = ...
So I can use utils.aFunction();
I also want to divide my dependencies in several files, as an example, this would be my project:
libs
|_ math.js //Implements randomInt and RandomFloat methods
|_ connection.js //Implements isConnected method
utils.js //Calls all the required dependencies
My idea so far is to have something like this:
In libs/math.js:
module.exports = {
randInt: function() {
return 4;
},
randFloat: function() {
return 4.1;
}
};
And then I would do in utils.js:
var math = require('./libs/math');
var connection = require('./libs/connection');
var libs = [math, connection];
var utils = {};
for (var i = 0; i < libs.length; i++) {
for (var key in libs[i]) {
utils[key] = libs[i][key];
}
}
window.utils = utils;
This actually works just fine, but I don't know if it wasn't already solved by a library.
I have a feeling there are more efficient ways of doing this, what would be the recommended approach with browserify?
The code for throwing things into util object is definitely odd looking, and I wouldn't recommend this looping over all your required util submodules.
var libs = [math, connection];
var utils = {};
for (var i = 0; i < libs.length; i++) {
for (var key in libs[i]) {
utils[key] = libs[i][key];
}
}
If you were using a common js approach with webpack/browserify, you would simply declare your util to be global in the configuration file, and simply add the needed module.exports inside of your util.js
//connect.js
module.exports = {
isConnected: function(){
return true;
}
};
//math.js
module.exports = {
randInt: function() {
return 4;
},
randFloat: function() {
return 4.1;
}
};
//utils.js
exports.math = require('./math');
exports.connect = require('./connect');
//test.js
var utils = require('./utils');
console.log(utils.math.randInt());
console.log(utils.connect.isConnected());

Mocha fails with variable not defined

I use mocha to test a function in a file. The testable function is implemented like this:
math.js
(function (exports) {
var MY_APP_ = MY_APP || {};
MY_APP_.utils = MY_APP_.utils || {};
MY_APP_.utils.math = MY_APP_.utils.math || {};
MY_APP_.utils.math.randomValue = function (min, max) {
return Math.floor(Math.random() * (max + 1 - min) + min);
};
exports.math = MY_APP_.utils.math;
})(this);
And here is the test:
math_test.js
var assert = require("assert");
var math = require("../../js/utils/math.js");
describe('Math', function() {
describe('randomValue', function () {
it('should return random values', function () {
// Fill array with random values between 0 and 10
var values = [];
for (var i = 0; i < 10000; i++) {
values.push(math.math.randomValue(0, 10));
}
// Count numbers
var result = {};
values.forEach(function(number) {
var numberAsString = number.toString();
result[numberAsString] = result[numberAsString] + 1 || 1;
});
// There must be at least two of each number
assert.equal(Object.keys(result).length, 11);
Object.keys(result).forEach(function(key) {
assert.equal(true, result[key] > 1);
});
});
});
});
The problem is that var MY_APP_ = MY_APP || {}; fails with an error message: MY_APP is not defined.
Sure, MY_APP is not defined in the scope of this test because it is defined in an another file called app.js. When I build the app, this app.js file is included before math.js and both of them are concatenated into a single production.js file. This works without problem.
The test works, however, if I replace the failing line with the following:
var MY_APP = {};
if (typeof(MY_APP) !== 'undefined') {
MY_APP_ = MY_APP;
} else {
MY_APP_ = {};
}
This looks stupid in my opinion. I would like to know the reason why mocha is failing since the code works perfectly well when I run it in a browser.
EDIT:
I think I have made a mistake. var MY_APP_ = MY_APP || {}; seems to never work if MY_APP is not defined so the only option is to declare MY_APP before using math.js
From what you showed I would think that you would receive an error, and that your direct test works.
In your test you initialize MY_APP to an empty object which allows it to run. But in your math.js file MY_APP is never initialized, so when you set var MY_APP = MY_APP it would never be able to set it to anything.
I would suggest trying to initialize MY_APP before assigning it as a value for a variable.
Since the only purpose of app.js to just initialize var MY_APP = {}; to global scope I decided to do the same in the test file, so:
var assert = require("assert");
global.MY_APP = {};
var math = require("../../js/utils/math.js");
solves the problem

Constructor Doesn't Initialize Online Javascript

I just need to reposition elements for app. The starts up locally but not deployed online. I am using "use strict" also.
var winHeight=$(window).height();
var winWidth=$(window).width();
var Layout = function(){
this.half=480;
this.targetX=960;
this.targetY=527;
this.resultX=0;
this.resultY=0;
this.compute= function(xx,yy){
var reX = xx-this.targetX;
var reY = yy-this.targetY;
var teX = reX+this.targetX;
var teY = reY+this.targetY;
this.resultX=teX/this.targetX;
this.resultY=teY/this.targetY
};
};
var layout = new Layout();
layout.compute(winWidth,winHeight);
You just need to say: function ClassName()
function Layout() {
...
};

Categories