Javascript Class variable reassign - javascript

I am creating a Class instance, I am kinda stuck on variable reassign, like below
class A {
constructor() {
this.checkBoolen = false
}
checkBoolen = false // error, asks to install #babel/plugin-proposal-class-properties to get support.
click() {
document.addEventListener('click', e => {
this.checkBoolen=true // <- a class constructor's prototype property can't be reassigned.
})
}
doSomthing() {
if(this.checkBoolen = true // <- never get there) {
console.log('do something')
setTimeout(function(){ this.checkBoolen = false}, 3000)
}
}
}
Looks like either I need to use #babel/plugin-proposal-class-properties? or change the Class to a function? I am wondering if there is a way to change variable inside Class or it is a bad practice?

There are multiple mismatch brackets, class keyword is uppercased
class A {
constructor() {
this.checkBoolen = false
}
checkBoolen = false // error, asks to install #babel/plugin-proposal-class-properties to get support.
click() {
document.addEventListener('click', e => {
this.checkBoolen=true // <- a class constructor's prototype property can't be reassigned.
});
}
doSomthing() {
if(this.checkBoolen = true )// <- never get there) {
console.log('do something')
}
}
And you can use it like this
let obj = new A();
obj.checkBoolen=true
obj.doSomthing()

I would not make my structure like this, but perhaps you should take a look.
class WTF{
constructor(clickElement){
this.clickElement = clickElement; this.checkBool = false;
clickElement.onclick = e => {
this.click();
console.log(this.checkBool);
}
}
click(){
this.checkBool = !this.checkBool;
return this;
}
}
let wtf = new WTF(document);
Just keep clicking on the page.

you have typeo
1- start class with lowercase class
2- check eventlistener syntax
class D {
constructor() {
this.checkBoolen = false;
}
checkBoolen = false // error, asks to install #babel/plugin-proposal-class-properties to get support.
click() {
document.addEventListener('click', (e) => {
this.checkBoolen=true; // <- a class constructor's prototype property can't be reassigned.
});
}
doSomthing() {
if(this.checkBoolen = true ) {
console.log('do something');
}
}
}

Related

Call method from one class when calling methods from another

I have two classes: first on checks that file exists and it's valid; second one make some stuff with that file:
class Validator {
constructor(){
this.file = './file.json';
}
check(){ ... }
}
class Modificator {
action1(){ ... }
action2(){ ... }
}
What I want is the method from first class automatically calls inside each method from the second class.
It's a bit tricky stuff, but I'm really don't want to do it manually, like so:
class Validator {
constructor(){
this.file = './file.json';
}
static check(){ ... }
}
class Modificator {
action1(){
let status = Validator.check();
...
}
action2(){
let status = Validator.check();
...
}
}
By using a wrapper
class Validator {
static check () {console.log('checked')}
static checkCbk (fn) {
return _ => {
this.check()
//then callback
fn()
}
}
}
class Modificator {
//via public instance field
action1 = Validator.checkCbk(function () {
console.log('mod::action1')
})
}
//or by prototype
Modificator.prototype.action2 = Validator.checkCbk(function(){
console.log('mod::action2')
})
var m = new Modificator()
m.action1()
m.action2()
However notice that if you were to subclass Modificator, you could forget to rewrap your methods...
By making a contract
More commonly by making a contract and delegating to implem if contract is fulfilled.
This way you don't have to worry when extending since check is made in base class anyway.
class Validator {
static check () {console.log('checked')}
}
class Contract {
action1 () {
Validator.check()
this._action1()
}
}
class M2 extends Contract {
_action1 () {
console.log('mod2::action1')
}
}
var m = new M2()
m.action1()

JS Class binding class variables

I have this Javascript class where in construct I initialize some class variable and I bind a click event and I try to get the declared variable if the click method is called, but returns every time undefined
class Tabs {
constructor() {
this.tabLinks = document.querySelectorAll('[data-tab]')
let self = this
if( this.tabLinks.length > 0 ) {
this.tabContainer = document.querySelectorAll('[data-target]')
this.tabLinks.forEach((el) => {
el.addEventListener("click", self.setActiveTab, false);
} )
}
return
}
setActiveTab(e) {
e.preventDefault()
let currentEl = e.target
console.log(currentEl)
console.log(this.tabLinks) // Is undefined
Tabs.tabLinks.forEach((el) => {
el.classList.remove("is-active")
} )
}
}
export default Tabs
what I do wrong in this case?

Class Scope with method called from subclass JS

I have a subclass that does some validation stuff that calls a method in the parent class that extends it, this is working in all places except when I need to access the local scope in the parent class, see example below
subclass
export default class ElementEvent extends Core {
constructor(events){
super(events);
this.validation = this.validateEvent();
this.element = this.getElement();
this.triggered = false;
this.player = false;
this.waitForElementDelay = 3000;
if (this.validation){
if (this.element){
this.processEvent();
} else {
this.waitForElement();
}
}
waitForElement(){
const interval = setInterval(()=>{
const el = this.getElement();
if (el){
this.element = el;
this.processEvent();
clearInterval(interval);
}
}, this.waitForElementDelay)
}
}
parent
export default class Reading extends ElementEvent {
constructor(event) {
super(event);
this.readingZoneHeight = 50;
this.wordsPerMinute = 300;
this.timer = 0;
}
processEvent() {
//this.elementEntryPoint = this.getElementEntryPoint();
//this.elementExitPoint = this.getElementExitPoint();
console.log(this);
console.log(this.readingZoneHeight);
window.addEventListener('scroll', () => {
console.log('Inside Event Listener ' + this.readingZoneHeight);
//this.handleWindowScroll();
});
}
}
When I console log this is shows a Reading class with all the props it should readingZoneHeight, wordsPerMinute etc but this.readingZoneHeight is undefined, however inside the event listener this.readingHeight is the correct value so not sure whats happening here?
Anyone Help?
That happens because you are calling the Reading's processEvent method from the constructor of the ElementEvent. So this is actually called as part of the super(event) call in the constructor of the Reading class.
And since the super(event) happens before you actually assign anything to the this.readingZoneHeight it is undefined at the time you log it.

Typescript: Extending Set in class causes error (Constructor Set requires 'new')

I'm trying to implement some basic operations to the Set object like says here
This is the code
export class Conjunto extends Set<any>{
constructor(initialValues?) {
super();
return new Conjunto(initialValues);
}
isSuperset(subset) {
//some code
}
}
Do you guys have any idea to make it work? or am I doing something wrong?
For the moment I'm using the hack this guy found here
if you are trying to add functions to the Set prototype, or add polyfills to Set, you can do the following:
declare global {
interface Set<T> {
// polyfill
isSuperset(subset: Set<T>) : boolean;
// new function
someNewFunc(): boolean;
}
}
// add polyfill to the Set prototype as mentioned in the doc you provided: https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Set
Set.prototype.isSuperset = function(subset) {
for (var elem of subset) {
if (!this.has(elem)) {
return false;
}
}
return true;
}
//add the new someNewFunc;
Set.prototype.someNewFunc = function() {
// some logic here...
return true;
}
to use:
stringSet = new Set<string>()
stringSet.isSuperset(someOtherSet);
stringSet.someNewFunc(); // returns true

If/else condition inside an Object

function Validator(formIsValid) {
if(this.formIsValid) {
alert('Form is valid!');
}
else {
alert('Form is invalid...');
}
}
Validator.prototype = { // Notice the .prototype here, it's important!
formIsValid: true,
enforceTextFieldMinLength: function(field, minLength) {
if (!field.value || field.value.length < minLength) {
this.formIsValid = false;
}
},
enforceLabelHasText: function(label) {
if (!label.text) {
this.formIsValid = false;
}
}
}
//var val = new Validator();
The above is my Val.js. This is how i am using in my otherFile.js
AddPatient.Firstname = FirstNameValue || Validator.enforceLabelHasText(FirstName);
I get an error saying cannot find function enforceLabelHasText in Object function Validator(formIsValid)
You can't put expressions in an object definition. If you want code to be executed after an object instance is created, you should use:
function Validator() {
if(this.formIsValid) {
alert('Form is valid!');
}
else {
alert('Form is invalid...');
}
}
Validator.prototype = { // Notice the .prototype here, it's important!
formIsValid: true,
enforceTextFieldMinLength: function(field, minLength) {
if (!field.value || field.value.length < minLength) {
this.formIsValid = false;
}
},
enforceLabelHasText: function(label) {
if (!label.text) {
this.formIsValid = false;
}
}
}
var a = new Validator();
This is a dummy solution; you will want to add arguments to the Validator() function, to initialize formIsValid and the other values. I suggest you should read the MDC's description on prototypes.
EDIT: If you went with the prototype solution, you need to call val.enforceLabelHasText(FirstName), after making val a global variable (either by omitting the var or by using var window.val = new Validator()).
This is not valid syntax.
You've dumped an if/else condition inside an object definition, like this:
var myObj = { a, b, c, d,
if (true) {
alert('WTF!');
}
};
Procedural code like this must be inside a function.
You can insert logic into an object literal, using an iife. Like this;
const testable = 1
const obj = {
a: 'value1',
b: (() => {
if (testable === 1) {
return 'testable was 1'
} else {
return 'testable was not 1'
}
})()
}
console.log(obj)
Validator is an object literal and you can only assign properties there, not arbitrary code.
You could assign a function which includes your code to a property.
Bind this to a variable in the beginning.
var that = this;
This keeps this changing and point to something else.
And use firebug!

Categories