Could someone poin-out why this works (JS , .bind() ) [duplicate] - javascript

This question already has answers here:
addEventListener calls the function without me even asking it to
(5 answers)
Accessing an object's property from an event listener call in JavaScript
(6 answers)
Closed 1 year ago.
can someone point out why the next code as soon as I open the live server webpage prompts me to input the number ( the one without .bind()) while the one with bind works flawlessly?
let chooseNumber;
const poll = {
question: ' What is your favorite programming language?',
options: ['0 : JavaScript', '1:Python', '2: Rust', '3:C++'],
//This generates [0,0,0,0]. More In the next section :D
answers: new Array(4).fill(0),
registerNewAnswer: function () {
chooseNumber = prompt(`${this.question} \n ${this.options}`);
if (chooseNumber >= 0 && chooseNumber < 4) {
this.answers[chooseNumber] = this.answers[chooseNumber] + 1;
}
console.log(this.answers);
console.log('Munem');
},
};
document
.querySelector('.poll')
.addEventListener('click', poll.registerNewAnswer.bind(poll)); //works
//
// document
// .querySelector('.poll')
// .addEventListener('click', poll.registerNewAnswer());
//doesn't work

Related

get items greater than given datetime and less than given datetime in an array [duplicate]

This question already has answers here:
Compare two dates with JavaScript
(43 answers)
Closed 2 years ago.
I have an array that has a startTime. I want to get items where startTime in between 2020-12-10 09:30:00 and 2020-12-10 13:20:00. I am using the filter method to get the items from the array.
startTime>'2020-12-10 09:30:00' // is working, returns array with 6 items
but when i add startTime>'2020-12-10 09:30:00' && startTime<'2020-12-10 13:20:00' // returns null
not able to understand why it not filtering the result when I use less than
here is my code
var empStart = empShift.filter(item => {
return item.startTime>'2020-12-10 09:30:00' && item.startTime<'2020-12-10
13:20:00'
})
Thanks for the response guys I came to know whats my mistake
var empStart = empShift.filter(item => {
return new date(item.startTime).getTime() >'2020-12-10 09:30:00' && new
date(item.startTime).getTime() <'2020-12-10 13:20:00'
})
new date(//variable).getTime() // solved my issue

What is this['string'](); in javascript and how it works; [duplicate]

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 2 years ago.
I searched in google but i could not find anything
test.js
class Hero(){
heroVar = 'hero1'
hero1() {
alert('I am Hero 1');
}
onClick(){
this[this.heroVar](); //this.heroVar value gets substituted with hero1
}
}
Is there any better use case,how this this[this.heroVar](); works,please explain,
does this also adds '.' in between 'this' and '[]' like this.hero1()
In Javascript class is an Object so
class Hero(){
heroVar = 'hero1'
hero1() {
alert('I am Hero 1');
}
onClick(){
this[this.heroVar](); //this.heroVar value gets substituted with hero1
// equal with this['hero1']()
// equal with hero1()
}
}

how can i make my function reusable whilst using the (e) parameter?

const days = document.querySelector('#days');
const hours = document.querySelector('#hours');
const minutes = document.querySelector('#minutes');
document.querySelector('#years').addEventListener('input', function (e) {
let years = e.target.value;
days.lastElementChild.innerHTML = years * 365;
hours.lastElementChild.innerHTML = years * 8760;
minutes.lastElementChild.innerHTML = years * 525600;
});
I really need help with this one. When using the e parameter i can target the value from when the event is triggered using this code. I get that i can call the parameter anything and use target to access all the juicy information about the event in the console. What i do nott understand is , why cant i pass arguments with the e to make my function reusable. I want to pass my variables via arguments and store placeholders as parameters and work against them. Instead if I store (e) as a parameter, unless i am missing something , I am forced to reference my variables inside my function because I cannot seem to pass other arguments with (e) . Is there a way i can e.target.value and still pass arguments to my function? This one has really got me stuck , thanks
One method is to record the id attribute values for output parent elements as a data attribute on the input element used to enter a year. Another method could involve setting up a table of parent elements using the id of the input as key.
A third option is to add the event listener (which is passed an event object as argument) inside a closure: i.e. inside an outer, reusable function which is called with all necessary argument values to add an event listener to a specific elements and handle events that are raised.
Here's an example of the first approach:
"use strict";
function showDHM(event) {
let years = event.target.value;
event.target.dataset.for.trim().split(/\s*,\s*/)
.map( id => document.getElementById( id))
.forEach( (element, index) => {
const multiplicand = [ 365, 8760, 525600];
element.lastElementChild.innerHTML = years * multiplicand[index];
});
}
const year1 = document.querySelector('#year1')
year1.dataset.for = "days1, hours1, mins1";
year1.addEventListener('input', showDHM);
<label> Year: <input type="number" id="year1"></lable>
<p>
<span id="days1"><span>days</span></span>,
<span id="hours1"><span>hours</span></span>,
<span id="mins1"><span>mins</span></span>
Note the code is for demonstration only: adjustment for leap years not included!
The next snippet demonstrates the closure option. The conversion process used to modify the posted code was largely mechanistic: replace hard-coded values with argument names and include the modified code in an outer function.
"use strict";
function handleYears( yearsSel, daysSel, hoursSel, minutesSel) {
const days = document.querySelector(daysSel);
const hours = document.querySelector(hoursSel);
const minutes = document.querySelector( minutesSel);
document.querySelector(yearsSel).addEventListener('input', function (e) {
let years = e.target.value;
days.lastElementChild.innerHTML = years * 365;
hours.lastElementChild.innerHTML = years * 8760;
minutes.lastElementChild.innerHTML = years * 525600;
});
}
handleYears("#year1", "#days1", "#hours1", "#mins1");
<label> Year: <input type="number" id="year1"></lable>
<p>
<span id="days1"><span>days</span></span>,
<span id="hours1"><span>hours</span></span>,
<span id="mins1"><span>mins</span></span>

javascript how to "fix" a variable inside a function, through eval? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have the following function
var label = function() {
return 'File: '+texts[t];
};
which is attached to highcharts, specified here
http://api.highcharts.com/highcharts#plotOptions.pie.dataLabels.formatter
where t has values let's say from 1 to 10 and text[t] corresponds to a different text. I attach this function to 10 highchart tooltips so that it executes the function with a mouseOver event.
The intended logic is that chart 1 has the text[1] label appearing, chart 6 has text[6], etc.
The problem is that all charts have the text[10] appearing, since t has that value when the function is executed.
How can I solve this? Is it a place for eval() like
var label = function() {
return 'File: '+eval(texts[t]);
};
UPDATE: based on comments, trying
var label = function(t) {
return 'File: '+t+' '+texts[t];
};
doesn't work as expected, it prints "File: [object Object] undefined"
This is a very common closure problem:
You probably have t in a for loop, just wrap the code which attaches the handler in another function:
// This will not work the way you might expect
// The value of i is left at 10 because that is the last
// time it is changed in the attacheHandlers1 scope held
// but the closure in the anonymous function used as a callback
// in setTimeout
//
function attachHandlers1(){
for(var i = 0; i < 10 ; i++){
setTimeout(function(){
console.log("Version 1", i);
}, 100)
}
}
// This works because the value is closured in
// attachHandlerImpl as 'x' with different values for
// each invocation
//
function attachHandlers2(){
for(var i = 0; i < 10 ; i++){
attachHandlerImpl(i);
}
}
function attachHandlerImpl(x){
setTimeout(function(){
console.log("Version 2", x);
}, 100);
}
attachHandlers1();
attachHandlers2();
Will output:
Version 1 10
Version 1 10
Version 1 10
Version 1 10
Version 1 10
Version 1 10
Version 1 10
Version 1 10
Version 1 10
Version 1 10
Version 2 0
Version 2 1
Version 2 2
Version 2 3
Version 2 4
Version 2 5
Version 2 6
Version 2 7
Version 2 8
Version 2 9
Without knowing the rest of your implementation details, something like this could work:
var texts = ['Text 1', 'Text 2', 'Text 3']
var label = function(idx) {
return "File: " + texts[idx];
};
label(2) returns "File: Text 3"

Run function passed from data attribute [duplicate]

This question already has answers here:
How to execute a JavaScript function when I have its name as a string
(36 answers)
Closed 7 years ago.
I want to be able to run a function that is passed by name from a data attribute on the HTML side. I've tried the following below.
HTML:
<div class="generic-select" data-help-on-shown="genericFunction" >
</div>
Javascript:
function genericFunction() {
console.log("generic function called");
}
Other Javascript (separate file):
//stepEl is correct divider from above
var genFunction = typeof (stepEl.data("helpOnShown")) === "undefined"
? null
: stepEl.data("helpOnShown");
//this prints "genericFunction" as expected
console.log("genFunction = " + genFunction);
if (genFunction) {
genFunction(); //gives error!
}
However, this gives me an error. Is there a way to call a function by a string name?
If the function is "global", it exists as a property of window:
window[functionname]()

Categories

Resources