On the time of page loaded get_switch() function which globally created on app.js page will be call then return a method. i want to execute these return methods.
demo.js
const return_functions = get_switch('BTC');
function get_btc()
{
console.log('btc');
}
function get_bch()
{
console.log('bch');
}
app.js
global.get_switch=function(coin_name){
switch(coin_name){
case 'BTC':
return 'get_btc()';
break;
case 'BCH':
return 'get_bth()';
break;
default:
console.log('default');
}
}
As shown in example above i have passed BTC in get_switch. and that function return us get_btc() function. so i want to call get_btc function on same time.
If this is not possible in this way so please guide me with your idea and suggest me how can i do this.
demo.js
var obj = {
get_btc: function get_btc() {
console.log('btc');
},
get_bth: function get_bth() {
console.log('get_bth');
}
}
const return_functions = get_switch('BTC');
if (return_functions) {
obj[return_functions]();
}
app.js
global.get_switch = function (coin_name) {
switch (coin_name) {
case 'BTC':
return 'get_btc';
break;
case 'BCH':
return 'get_bth';
break;
default:
console.log('default');
}
}
var get_switch=function(coin_name){
switch(coin_name){
case 'BTC':
get_btc();
break;
case 'BCH':
get_bth();
break;
default:
console.log('default');
}
}
get_switch('BTC');
function get_btc() {
console.log('btc');
}
function get_bch() {
console.log('bch');
}
Related
I have NodeJS program.
In one class, I have various utility methods. One function, safeGithubPush, calls safeString, another func in the same class
module.exports = {
safeString(stringToCheck) {
console.log(validator.isAscii(stringToCheck), validator.matches(stringToCheck, /^((\w)*[-.]?(\w)*)*$/))
return (
validator.isAscii(stringToCheck) &&
validator.matches(stringToCheck, /^((\w)*[-.]?(\w)*)*$/)
);
},
safeGithubPush(currentJob) {
if (
!currentJob ||
!currentJob.payload ||
!currentJob.payload.repoName ||
!currentJob.payload.repoOwner ||
!currentJob.payload.branchName
) {
this.logIn(
currentJob,
`${' (sanitize)'.padEnd(15)}failed due to insufficient job definition`
);
throw invalidJobDef;
}
if (
this.safeString(currentJob.payload.repoName) &&
this.safeString(currentJob.payload.repoOwner) &&
this.safeString(currentJob.payload.branchName)
) {
return true;
}
throw invalidJobDef;
},
}
While this.logIn(), another func in the utility class, works just fine, I get the error for safeString:
Error caught by first catch: TypeError: this.safeString is not a function
I followed a solution offer by another SO post:
safeString: function(stringToCheck){
...
}
safeGithubPush(currentJob) {
...
if (
this.safeString(currentJob.payload.repoName) &&
this.safeString(currentJob.payload.repoOwner) &&
this.safeString(currentJob.payload.branchName)
) {
return true;
}
}
But this also gets a, TypeError: this.safeString is not a function.
I'm not using arrow functions, which is the explanation for this error on a different SO post
I don't think the reason is determinable with the code you are currently presenting. It likely has something to do with how you are calling safeGithubPush. If you do something that would change the this binding the this.safeString is going to fail.
const foo = {
fizz() {
console.log("fizz");
},
buzz() {
this.fizz();
}
};
// "this" is correct
foo.buzz();
// "this" has no fizz to call
const myFizz = foo.buzz;
myFizz();
Considering you are attaching these to module.exports I am going to guess that you pull these functions off in a require call and then try to use them bare which makes the problem obvious after looking at my example above:
// Ignore these 2 lines, they let this look like node
const module = {};
const require = () => module.exports;
// Ignore above 2 lines, they let this look like node
// Your module "some.js"
module.exports = {
safeString(str) {
return true;
},
safeGithubPush(currentJob) {
if (!this.safeString("some")) {
throw new Error("Not safe");
}
return true;
}
};
try {
// Some consumer module that doesn't work
const {safeGithubPush} = require("./some.js");
const isItSafe = safeGithubPush();
console.log(`Safe? ${isItSafe}`);
} catch (err) {
console.error("Didn't bind right \"this\"");
}
try {
// Some consumer module that DOES work
const someModule = require("./some.js");
const isItSafe = someModule.safeGithubPush();
console.log(`Safe? ${isItSafe}`);
} catch (err) {
console.error(err);
}
I would restructure this code. You say these are utility functions which makes me think you don't really want to have to structure them with this in mind.
Instead of attaching them all to module.exports at their definition, define them outside and directly reference the functions you want to use, then attach them to exports so other modules can use the functions:
function safeString(stringToCheck) {
return true;
}
function safeGithubPush(currentJob) {
if (!safeString("some")) {
throw new Error("Not safe");
}
return true;
}
module.exports = {
safeString,
safeGithubPush
};
I am making a simple note taking app to learn node and ES6. I have 3 modules - App, NotesManager and Note. I am importing the Note class into the NotesManager and am trying to instantiate it in its addNote function. The problem is that even though the import is correct, it turns out to be undefined inside the class definition. A simpler solution would be to just instantiate the NotesManager class and add the Note class to its constructor however, I want to have NotesManager as a static utility class.
Here is my code.
Note.js
class Note {
constructor(title, body) {
this.title = title;
this.body = body;
}
}
module.exports = Note;
NotesManager.js
const note = require("./Note");
console.log("Note: ", note); //shows correctly
class NotesManager {
constructor() {}
static addNote(title, body) {
const note = new note(title, body); //Fails here as note is undefined
NotesManager.notes.push(note);
}
static getNote(title) {
if (title) {
console.log(`Getting Note: ${title}`);
} else {
console.log("Please provide a legit title");
}
}
static removeNote(title) {
if (title) {
console.log(`Removing Note: ${title}`);
} else {
console.log("Please provide a legit title");
}
}
static getAll() {
//console.log("Getting all notes ", NotesManager.notes, note);
}
}
NotesManager.notes = []; //Want notes to be a static variable
module.exports.NotesManager = NotesManager;
App.js
console.log("Starting App");
const fs = require("fs"),
_ = require("lodash"),
yargs = require("yargs"),
{ NotesManager } = require("./NotesManager");
console.log(NotesManager.getAll()); //works
const command = process.argv[2],
argv = yargs.argv;
console.log(argv);
switch (command) {
case "add":
const title = argv.title || "No title given";
const body = argv.body || "";
NotesManager.addNote(title, body); //Fails here
break;
case "list":
NotesManager.getAll();
break;
case "remove":
NotesManager.removeNote(argv.title);
break;
case "read":
NotesManager.getNote(argv.title);
break;
default:
notes.getAll();
break;
}
Is it possible for me to create a strict utility class which I can use without instantiating like in Java? Pretty new here and have tried searching for it without any luck. Thank you for your help.
When you do this:
const note = new note(title, body);
you redefine note shadowing the original note from the outer scope. You need to pick a different variable name.
Something like this should work better:
static addNote(title, body) {
const some_note = new note(title, body); //Fails here as note is undefined
NotesManager.notes.push(some_note);
}
How can we clone an object in Polymer?
Example
this.colorsAsc.push({color: 'red'});
this.colorsDesc = this.colorsAsc.reverse();
this.colorsDesc[0].color = 'blue'; // Both will be blue doing this
I can do it in these many functionalities What is the most efficient way to deep clone an object in JavaScript? but I wonder if there is a way in Polymer to do that?
Angular does it https://docs.angularjs.org/api/ng/function/angular.copy
You can try the following hack:
this.colorsDesc = JSON.parse(JSON.stringify(this.colorsAsc.reverse());
I have had the same question here, where I have finally also found and posted an answer.
Short version:
newElement = element.cloneNode(true);
for(var i in element.properties) {
newElement[i] = element[i]
}
To clone a utility via Polymer
Full implementation:
(function(callBackFn) {
Polymer({
//Component Name
is: 'my-cloner',
properties: {
//Declare a published property
cloneableObject: { //Placeholder for Object to be cloned
reflectToAttribute: true,
type: Object,
notify: true
}
},
attached: function() {
//Hide if this component got attached
this.hidden = true;
},
getClone: function(incomingcloneableObject) { //Will be called to get the Clone
this.cloneableObject = this.cloneableObject || incomingcloneableObject;
switch (typeof this.cloneableObject) {
case "undefined":
return null;
break;
case "object":
var localClone = this.cloneNode();
return (localClone.cloneableObject);
break;
case "boolean":
return new Boolean(this.cloneableObject).valueOf();
//Other possible way
//return(this.cloneableObject ? true : false);
break;
case "number": //NaN is taken care of
return new Number(this.cloneableObject).valueOf();
//Other possible way
//return(this.cloneableObject * 1);
break;
case "string":
return new String(this.cloneableObject).valueOf();
//Other possible way
//return(this.cloneableObject + '');
break;
default:
return null;
}
}
});
//adding Util into window
callBackFn();
})(function() {
window.cloneUtil = document.createElement('my-cloner');
});
//To use this util
//window.cloneUtil.getClone();
I'm using chrome.storage in an extension and would like to avoid triggering runtime errors due to exceeding one of the documented throttles for either the sync or local stores. (things like QUOTA_BYTES, QUOTA_BYTES_PER_ITEM)
My first choice would be to intercept these errors prior to a runtime error being generated; alternatively I could track usage on the extension side and try to avoid triggering them.
This feels like an issue that someone must have addressed, but I can't seem to find any solutions - any suggestions appreciated.
Here's a sample of the solution I'm going with (using Angular, so there are promises in here), although having to regex the chrome.runtime.lastError value is pretty ugly IMO:
var service = {
error: function(lastError) {
if((lastError) && (lastError.message)) {
var errorString = lastError.message;
if(/QUOTA_BYTES/.test(errorString)) {
return true;
} else if(/QUOTA_BYTES_PER_ITEM/.test(errorString)) {
return true;
} else if(/MAX_ITEMS/.test(errorString)) {
return true;
} else if(/MAX_WRITE_OPERATIONS_PER_HOUR/.test(errorString)) {
return true;
} else if(/MAX_SUSTAINED_WRITE_OPERATIONS_PER_MINUTE/.test(errorString)) {
return true;
}
return false;
} else {
return false;
}
},
write: function(key, value) {
var deferred = $q.defer();
var data = {};
data[key] = value;
chrome.storage.sync.set(data, function() {
if(service.error(chrome.runtime.lastError)) {
deferred.reject('Write operation failed: '
+ chrome.runtime.lastError.message);
} else {
deferred.resolve();
}
});
return deferred.promise;
}
};
return service;
I am trying to modify comment body before saving or updating in drupal 6. I am trying to use following code:
function mymodule_comment(&$a1, $op) {
switch ($op) {
case 'insert':
case 'update':
$a1['comment'] = myfunction($a1['comment']);
break;
}
}
But it is not updating the comment body after save. I also tried following code and it works:
function mymodule_comment(&$a1, $op) {
switch ($op) {
case 'insert':
$a1['comment'] = myfunction($a1['comment']);
comment_save($a1);
break;
}
}
But in case of update it is showing error:
function mymodule_comment(&$a1, $op) {
switch ($op) {
case 'update':
$a1['comment'] = myfunction($a1['comment']);
comment_save($a1);
break;
}
}
Any idea or help is very appreciated.
Ok I got the work around. first create a hook_form_alter function:
mymodule_form_alter($form,$form_state,$form_id){
if ($form_id == 'comment_form') {
$form['#submit'][] = 'mymodule_comment_form_submit';
}
}
Then create hook_comment_form_submit function and do your modification:
mymodule_comment_form_submit($form, $form_state){
$form_state['values']['comment'] = myfunciton($form_state['values']);
comment_save($form_state['values']);
}
I dont know whether it is a good idea or not but I found few of post in which this approach is used.