How to declare and access global variable - javascript

What Im doing wrong in the below code?
//File1.js
var arr = [];
function insertName {
var name = "josh";
arr.push(name);
return name;
};
function validName(key) {
var index = arr.indexOf(key);
if (index == -1) {
return false;
} else {
return true;
}
}
var result = insertname();
exports.arr = arr;
exports.validName = validName;
//File2.js
var file1 = require("./File1.js");
var name = "josh";
var verify = file1.validName(name);
if(verify) {
cosnole.log("Valid name");
}else {
console.log("Error");
}
node File1.js
node File2.js
When Im executing File2.js, Im gettin undefined for arr[]. Can someone help me what Im doing in the below code

Node.js modules retain the variables you declared at their top level, till the module is Garbage Collected or you manually delete them. If you look at your File1.js, you are exporting the array object, nothing else. So when you say
var file1 = require("./File1.js");
file1 is just a reference to a JavaScript object which has an arr property. You can check this by printing the file1. The functions you created in File1 are never exported. So, you can fix it like this*
exports = module.exports = {
validName: validName,
insertName: insertName
}
Now, you are exporting the functions and they can still access the arr variable. From File2, you can invoke insertName like this
file1.insertName();
if (file1.validName("josh")) {
console.log("Valid name");
} else {
console.log("Error");
}
* To know more about exports and module.exports, you can check my blog post about this

Your code contains mistakes change your code like below
File1.js
var arr = [];
function insertName() {
var name = "josh";
arr.push(name);
return name;
};
function validName(key) {
var index = arr.indexOf(key);
if (index == -1) {
return false;
} else {
return true;
}
}
var result = insertName();
exports.validName = validName;
File2.js
var file1 = require("./File1.js");
var name = "josh";
var verify = file1.validName(name);
if(verify) {
console.log("Valid name");
} else {
console.log("Error");
}

You can simply use global.(name) = (value)
Example :
main.js
global.foo = 1;
require('./mod.js').show();
mod.js
module.exports = {
show : function(){
console.log(global.foo); // which prints "1"
}
}

Related

Javascript & knockoutjs: how to refactor the following code to be able to access the properties outside the function

Im struggling to find a way to get the properties Override & Justification available outside of the function. The code is:
self.CasOverridesViewModel = ko.observable(self.CasOverridesViewModel);
var hasOverrides = typeof self.CasOverridesViewModel === typeof(Function);
if (hasOverrides) {
self.setupOverrides = function() {
var extendViewModel = function(obj, extend) {
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
extend(obj[property]);
}
}
};
extendViewModel(self.CasOverridesViewModel(), function(item) {
item.isOverrideFilledIn = ko.computed( function() {
var result = false;
if (!!item.Override()) {
result = true;
}
return result;
});
if (item) {
item.isJustificationMissing = ko.computed(function() {
var override = item.Override();
var result = false;
if (!!override) {
result = !item.hasAtleastNineWords();
}
return result;
});
item.hasAtleastNineWords = ko.computed(function() {
var justification = item.Justification(),
moreThanNineWords = false;
if (justification != null) {
moreThanNineWords = justification.trim().split(/\s+/).length > 9;
}
return moreThanNineWords;
});
item.isValid = ko.computed(function() {
return (!item.isJustificationMissing());
});
}
});
}();
}
I've tried it by setting up a global variable like:
var item;
or
var obj;
if(hasOverrides) {...
So the thing that gets me the most that im not able to grasp how the connection is made
between the underlying model CasOverridesviewModel. As i assumed that self.CasOverridesViewModel.Override() would be able to fetch the data that is written on the screen.
Another try i did was var override = ko.observable(self.CasOverridesViewModel.Override()), which led to js typeError as you cannot read from an undefined object.
So if anyone is able to give me some guidance on how to get the fields from an input field available outside of this function. It would be deeply appreciated.
If I need to clarify some aspects do not hesitate to ask.
The upmost gratitude!
not sure how far outside you wanted to go with your variable but if you just define your global var at root level but only add to it at the moment your inner variable gets a value, you won't get the error of setting undefined.
var root = {
override: ko.observable()
};
root.override.subscribe((val) => console.log(val));
var ViewModel = function () {
var self = this;
self.override = ko.observable();
self.override.subscribe((val) => root.override(val));
self.load = function () {
self.override(true);
};
self.load();
};
ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

Custom script in Meteor

I just started playing with Meteor and i was testing few things. Based on the Meteor Guide i was testing below code to understand the best way to write packages but i never been successful. What is wrong with the following code and what is good way (if not all but atleast few good ways) to write the packages for Meteor app which can be placed in lib folder.
/lib/exports.js
if (org === void 0){
var org = {}
}
if(bjse === void 0){
var bjse = {};
if(typeof exports != "undefined"){
bjse = exports;
}
bjse.api = {};
}
/lib/file1.js
// mypackage.js
bjse.api.Whirlygig = function (name) {
var self = this;
self.name = name; // name of the remote weasel
self.values = {}; // remote key name -> 0-indexed value
};
_.extend(Whirlygig.prototype, {
// Take a key/value pair from the remote Weasel and save it locally.
addValue: function (x) {
// Weasels use 1-indexed arrays. Subtract 1 to convert to 0-indexed.
self.values[x.key] = x.value - 1;
},
// Return a list of stored values in a format suitable for sending to
// a Weasel.
serialize: function () {
return _.map(self.values, function (v, k) {
var newVal = mungeValue(v, false /* foldValue */);
// Weasels use 1-indexed arrays. Add 1 to convert back to 1-indexed.
newVal = newVal + 1;
return {key: k, value: newVal};
});
}
});
/server/methods.js
Meteor.methods({
createConnections: function(){
....
var serializeObj = bjse.api.Whirlygig.serialize(..);
But i get Whirlygig not defined.
Update
I want to use bjse as namespace but it always appears as not defined in other files.
In exports you want:
if (typeof(org) === 'undefined'){
var org = {}
}
if(typeof(bjse) === 'undefined'){
var bjse = {};
if(typeof exports != "undefined"){
bjse = exports;
}
bjse.api = {};
}

Using Titanium framework to create global array

I have three js controller file and 1 lib
app/lib/Client
function Client(id,name,blc){
this.id=id;
this.name=name;
this.blc=blc;
};
Client.prototype.getName = function(){
return this.id+' '+this.name+' '+this.blc;
};
Client.prototype.withdraw = function(amount){
if(amount<0) return -1;
if(this.blc<amount) return -1;
return this.blc-=amount;
};
Client.prototype.deposite = function(amount){
if(amount<0) return -1;
return this.blc+=amount;
};
module.exports = Client;
app/controller/addClient //this is where I want to add to global array
var args = arguments[0] || {};
var Client = require('Client');
function doClick(e) {
var user_id = $.id.getValue();
var user_name = $.name.getValue();
var user_blc = $.Balance.getValue();
if(user_id.length<=0 && user_name.length<=0 && user_blc.length<=0){
alert('you entred an invalid information');
}
else{
var c = new Client(user_id,user_name,user_blc);
alert(c.getName()+' is add successfly');
//note!!!!!
//add a global array to save the data
$.id.setValue("");
$.name.setValue("");
$.Balance.setValue("");
}
}
$.addClient.open();
app/controller/allClient
//this is where i want to use the data in Global app to make a listView
If you really want a "global array" use Alloy.Globals
If you want a collection of models, use Backbone

Associate a string with a function name

I have a text input that I want to enable users to call functions from.
Essentially I want to tie strings to functions so that when a user types a certain 'command' prefaced with a backslash the corresponding function is called.
Right now for example's sake you can type /name, followed by a value and it will set name as a property of the user object with the value the user gives.
So how would I do this with 20 or so 'commands'?
http://jsfiddle.net/k7sHT/5/
jQuery:
$('#textCommand').on('keypress', function(e) {
if(e.keyCode==13) {
sendConsole();
}
});
var user = {};
var sendConsole = function() {
value = $('#textCommand').val();
if (value.substring(0,5) === "/name") {
user.name = value.substring(6,20);
alert(user.name);
} else {
$('body').append("<span>unknown command: "+value+"</span><br />")
$('#textCommand').val("");
}
}
HTML:
<input id="textCommand" type="text"><br/>
Store your functions in an object, so you can retrieve and call them by key:
// Store all functions here
var commands = {
name : function() {
console.log("Hello");
}
}
var sendConsole = function() {
value = $('#textCommand').val();
// Strip initial slash
if(value.substring(0,1) === '/') {
value = value.substring(1);
// If the function exists, invoke it
if(value in commands) {
commands[value](value);
}
}
}
http://jsfiddle.net/NJjNB/
Try something like this:
var userFunctions = {
run: function(input)
{
var parts = input.split(/\s+/);
var func = parts[0].substr(1);
var args = parts.slice(1);
this[func].call(this, args);
},
test: function(args)
{
alert(args.join(" "));
}
};
userFunctions.run("/test hello there"); // Alerts "hello there".
You can do:
if(window["functionName"])
{
window["functionName"](params);
}

I have no idea how to test this with Qunit?

I want to test this function:
/js/lib/front.js
var Front = function(){
this.onSignUp = function(){
if (!Form.assertInput("email")) {
$("input[name=email]").focus();
this.showHiddenMessage("Email not set.");
return false;
}
}
}
I have in:
/js/lib/form.js
function Form() {
this.assertInput = function (name, defaultValue) {
var text = $("input[name=" + name + "]").val();
if (defaultValue != null) {
if (defaultValue && text == defaultValue)
return false;
}
if(this.trim(text)) return true;
return false;
}
}
This simple test passing:
test("Front", function() {
var front = new Front()
ok(front);
});
But if I write something like this:
test("On Sign Up ", function() {
var front = new Front()
equal(front.onSignUp(),false,"passing test");
});
I have error:
Died on test #1: Form.assertInput is not a function
I don't understand, what I need test in function like this and how include function inside another function?
I've saved a working fiddle here. As a side note, you might want to check out a tutorial on using qUnit, here.One thing that you need to pay attention to is when you're declaring your functions. It's saying Form.assertInput is not a function because you can't access it like that. You need to use the this keyword, which refers to current context. The code should be something like this:
var Form = function () {
//good to have assertInput first if you're using it in a later function
this.assertInput = function (name, defaultValue) {
var text = $("input[name=" + name + "]").val();
if (defaultValue != null) {
//safer to explicitly close your if statements with {}
if (defaultValue && text == defaultValue) {
return false;
}
}
if ($.trim(text)) { return true; }
return false;
};
this.showHiddenMessage = function (message) {
alert(message);
};
this.onSignUp = function() {
//this will point to the current context, in this case it will be Form class
if (!this.assertInput("email")) {
$("input[name=email]").focus();
this.showHiddenMessage("Email not set.");
return false;
}
};
};
Also in the example code that you gave you're missing the Front class. So I created a dummy one in my fiddle like this:
var Front = function() {};
Here are the tests that were run:
$(document).ready(function() {
test("Front", function() {
var front = new Front();
ok(front);
});
test("On Sign Up ", function() {
var form = new Form();
equal(form.onSignUp(), false, "passing test");
});
});

Categories