Associate a string with a function name - javascript

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);
}

Related

Calling another function after value is not working

I have a simple code to call a value from another function and its not working :
function ABC() {
var ID = XYZ(id);
Logger.log(ID); //throws error not defined.
}
function XYZ(id) {
var id = "1234"
return id;
}
What I wan to do is capture the value of id from function XYZ and Logger.log it into function ABC. But this reflects error.
Still not sure what you are trying to do with your code. This code is an "Impure Function" which is not recommended in JavaScript. How much I understood your code, below are my suggestions:
First
function abc() {
var id = xyz();
Logger.log(id);
}
function xyz() {
// Add whatever logic you want here to return ID value
var id = "1234"
return id;
}
Second
function abc() {
// Pass any value as an argument based on your requirement
var results = xyz('', '', '');
Logger.log(results.id);
Logger.log(results.name);
Logger.log(results.number);
}
function xyz(id, name, number) {
// Add whatever logic you want here
var newId = id || "1234";
var newName = name || "Mask";
var newNumber = number || "1234567890";
return { id: newId, name: newName, number: newNumber };
}
Based on what suits your requirement, you can take help of these codes.
Here you go -
function ABC() {
var ID = XYZ();
Logger.log(ID); // No longer throws the error :)
}
function XYZ() {
var id = "1234"
return id;
}
You do not need two functions, here is a simple function that will return the ID passed in.
const ABC = (id) => {
return id;
}
let a = ABC(122443);
console.log(a) // output 122443

How to declare and access global variable

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"
}
}

How to call a function on string jQuery

I was reading through fluent api I got a doubt.
I want to take in a string upon which a jQuery function or example is called upon
Function
function compareThis(newString) {
function compare(newString) {
if (this == newString) {
alert("same string");
} else {
alert("differnt string");
}
}
}
Where it is called as
("alerting").compareThis("alerted").compare(); //alert 'different string'
I want to pass the data/string not as parameter but as called upon.
JSFiddle
Note: I would like to call the function in similar cases like finding date interval etc
You can use prototype to add function to String class:
String.prototype.compare = function(newString){
if (this == newString) {
alert("same string");
} else {
alert("differnt string");
}
};
I think you should adapt the code for your function, but it's the idea.
Maybe I missed interpreted however, it looks as it you required a form of method chaining to compare string. To do this you can create a variable and create functions inside it.
var compare = (function(){
var thisString;
var stringToCompare;
var create = function(sVal) {
thisString = sVal;
return this;
};
// Public
var compareThis = function(sVal) {
stringToCompare = sVal;
return this;
};
var compare = function(anotherString) {
return thisString == stringToCompare;
};
return {
create: create,
compareThis: compareThis,
compare: compare
};
}());
var b = compare.create('test').compareThis('test').compare();
alert(b);
Example fiddle

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");
});
});

Resolve function pointer in $(document).ready(function(){}); by json string name

I have a json object retrieved from server in my $(document).ready(...); that has an string that I would like to resolve to a function also defined within $(document).ready(...); so, for example:
$(document).ready(function{
$.getJSON(/*blah*/,function(data){/*more blah*/});
function doAdd(left,right) {
return left+right;
}
function doSub(left,right) {
return left-right;
}
});
with json string:
{"doAdd":{"left":10,"right":20}}
One way I thought about was creating an associative array of the function before loading the json:
var assocArray=...;
assocArray['doAdd'] = doAdd;
assocArray['doSub'] = doSub;
Using eval or window[](); are no good as the function may not be called for some time, basically I want to link/resolve but not execute yet.
Change your JSON to
{method: "doAdd", parameters : {"left":10,"right":20}}
Then do
var method = eval(json.method);
// This doesn't call it. Just gets the pointer
Or (haven't tried this)
var method = this[json.method]
How about something like this?
$(function(){
// Function to be called at later date
var ressolvedFunc = null;
// Ajax call
$.getJSON(/*blah*/,function(data){
// Generate one function from another
ressolvedFunc = (function(data) {
var innerFunc;
var left = data.left;
var right = data.right;
// Detect action
for (action in data) {
if (action == "doAdd")
innerFunc = function() {
return left + right;
};
else
innerFunc = function() {
return left - right;
};
}
return innerFunc;
})(data);
});
});
The anonymous function returns fresh function, with the new values stored within the enclosure. This should allow you to call the function at later date with the data previously retrieved from the GET request.
Rich
try this:
var doX = (function() {
var
data = [],
getDo = function(action) {
for(var d in data) {
if (data[d][action]) {
return data[d];
}
}
return null;
};
return {
set: function(sdata) {
data.push(sdata);
},
doAdd: function() {
var add = getDo("doAdd");
if (!add)
return 0;
return add.doAdd.left + add.doAdd.right;
},
doSub: function() {
var sub = getDo("doSub");
if (!sub)
return 0;
return sub.doAdd.left + sub.doAdd.right;
}
};
})();
$(document).ready(function{
$.getJSON(/*blah*/,function(data){ doX.set(data); });
});

Categories