How to use a local variable in javascript function [duplicate] - javascript

This question already has answers here:
Javascript: Object Literal reference in own key's function instead of 'this'
(5 answers)
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 1 year ago.
Apologies if the terminology is off - javascript isn't my thing.
I have a function:
var input = {
getVal: function () {
return $(this).attr("data-current-val");
},
setVal: function () {
$(this).attr("data-current-val", $(this).val());
},
valHasChanged: function () {
return $(this).val() !== $(this).attr("data-current-val");
}
};
As you can see there is some repetition. Firstly, I repeat the data attribute name several times; secondly, I select a jquery object numerous times.
I've tried to remove the repetition. For instance, in respect of the data attribute, by adding node: "data-current-val" at the top and then calling it with this.node in place of the string. That causes an error, as does trying to define and then use the jquery objectin the same way.
Similarly part of the boolean in valHasChanged $(this).attr("data-current-val"), logically could be replaced by this.getVal but that doesn't seem to work either. Where am I going wrong?!
Any help appreciated.

Related

Is it possible to convert e.target.property to a value and use it to reference an object? [duplicate]

This question already has answers here:
Convert string to variable name in JavaScript
(11 answers)
"Variable" variables in JavaScript
(9 answers)
Closed 5 years ago.
The simplified code below does not work but I hope it helps to illuminate the idea I'm testing.
e.target.id returns the name of the id that initiated the function call. In this case it's the id target. Since target is also an object I thought maybe I could reference a key inside the target object. In this case .name. As structured this does not work at all. Do I need to process e.target.id before I use it as a reference? Is this possible at all?
1) I'm aware this might possibly be categorized under worst practices.
2) I'm testing how far I can push JS.
'use strict';
var target = {
name: 'it worked'
}
document.getElementById('target').addEventListener('click', myFunction);
function myFunction(e) {
alert(e.target.id.name); //dies right here
}
<div id="target"></div>
You could do this with eval or as #Slai mentioned with window[e.target.id].
Be careful with eval:
Why is using the JavaScript eval function a bad idea?
var target = {
name: 'it worked'
}
document.getElementById('target').addEventListener('click', myFunction);
function myFunction(e) {
//alert(eval(e.target.id).name);
alert(window[e.target.id].name);
}
<div id="target">div</div>

Dynamically call function in javascript [duplicate]

This question already has answers here:
Calling function inside object using bracket notation
(2 answers)
Closed 6 years ago.
I rather have a seemingly trivial issue, but am not able to figure out an efficient approach.
I have a list of about 50 functions to be called such as :
globalClient.funcA(...)
globalClient.funcB(...)
globalClient.funcC(...)
My code should ideally dynamically create the name of the function (funcA / funcB/ funcC and then proceed to actually call that function. My approach below does not work (please note that these aren't exactly the actual names of the functions. I'm only giving these arbitrary names for simplicity of understanding):
var functionName = 'func'.concat('A');
globalClient.functionName
The second line is where it errors out. Now JS thinks that functionName itself is the name of the function. What I want it to do is resolve functionName to funcA and then call globalClient.funcA(...) instead.
I've thought about implementing a switch / case for this but I'm sure there is a far simpler appraoch. Any ideas?
You could use the bracket notation as property accessor.
globalClient[functionName]()
You can use the [ ] operator for accessing the properties.
var globalClient = {
funcA: function(){
console.log('funcA is called');
}
}
var functionName = 'func'.concat('A');
globalClient[functionName]();

Javascript: Why name object method functions [duplicate]

This question already has answers here:
Why use named function expressions?
(5 answers)
Closed 6 years ago.
In some projects I can see, that the functions wich are object methods get names after the function constructor - I can not see why, can any one explain?
Example: named
someObj.prototype = {
load: function someObj_load(file) {
vs unnamed
someObj.prototype = {
load: function(file) {
I can not see any advantage in the above.
So you can see the name of the function name instead of Anonymous function in stack traces. I think some browsers will pick up the name of the variable/attribute you've assigned it to. Some don't.

Click Event Closure Inside Loop [duplicate]

This question already has answers here:
Javascript infamous Loop issue? [duplicate]
(5 answers)
Closed 8 years ago.
I have a click event attached to an element via JQuery in a loop (loop variable i):
$('#id_'+i).click(function() {ItemClick(i)});
And defined somewhere else:
function ItemClick(x) {
alert(x);
}
As expected, this doesn't work as expected, because of the closure. I'd like to see a different number shown for each different click event, instead I just get the last value of i.
I know I need to turn the i in the closure to something that somehow isn't attached to the scope of the closure, but it eludes me, even after trying various examples. Such as:
$('#id_'+i).click(function() {ItemClick(function(x){return x)(i))});
Is there a neat and concise way of doing this?
EDIT
After looking at the duplicate, I now have two answers (please close the question):
Answer A
$('#id_'+i).data('index',i);
$('#id_'+i).click(
function() {
ItemClick($(this).data('index'));
}
);
Answer B
$('#id_'+i).click(
function(index) {
return function () {
ItemClick(index)
};
}(i)
);
This is a very common javascript issue that occurs because Javascript is closure/scope based, not block based.
You can fix this by creating a closure around your function call.
$('#id_' + i).on('click', function() {
(function (index) {
ItemClick(index);
}(i));
});
jsFiddle Demo

what's the purpose and meaning of e in jquery code [duplicate]

This question already has answers here:
jquery/javascript: function(e){.... what is e? why is it needed? what does it actually do/accomplish?
(4 answers)
What is the purpose of this? (function ($) { //function code here })(jQuery);
(4 answers)
Closed 8 years ago.
In the following code, there are two 'e's, are they about the same object/type or actually about different things?
(function(e) {
var t = {
init: function() {
e(".pic").length && this.show()
}
};
window.Booth = t;
})(jQuery);
Also, I am a little confused with the overall semantics of the code snippet above, any documentation out there can explain it?
In this case, it's an alias for jQuery. Usually people use $, but in this case they didn't.
what you have is an anonymous, self-executing function.
the function is passed the jquery object (which is a function). e(".pic") is the same as $(".pic") or jQuery(".pic") because e is just a reference to jQuery.

Categories

Resources