1

I am new to reactJs and I am having an issue with undefined function.

As I see I define it at my constructor, but..

bundle.js:758 Uncaught ReferenceError: myCallback is not defined.

import React from "react";
import ReactDOM from "react-dom";
import Vivus from "vivus";

export default class MySkills extends React.Component {
    constructor() {
        super();
        this.state = {visable: false};
        this.onScroll = this.onScroll.bind(this);
        this.myCallback = this.myCallback.bind(this);
    }

    componentDidMount() {
        document.addEventListener('scroll', this.onScroll);
    }

    myCallback() {
       alert("myCallback");
    }

    onScroll() {
        var scrollY = window.scrollY;
        if (scrollY > 2300 && this.state.visable === false) {
            new Vivus("foo", {duration: 100, file: 'bar'}, myCallback.bind(this));
    }
}

Maybe somebody can explain better the binding of functions? It seems to be working with the onScrool function, but the myCallback function is not working.

Thank You!

1 Answer 1

2

You have the binding in your constructor (which I don't recommend) so you can just write change this

new Vivus("foo", {duration: 100, file: 'bar'}, myCallback.bind(this));

to this

new Vivus("foo", {duration: 100, file: 'bar'}, this.myCallback);

Or you can skip the bindings in the constructor and use this

new Vivus("foo", {duration: 100, file: 'bar'}, this.myCallback.bind(this));

Or you can skip the bindings in the constructor and use an arrow function (my personal recommendation)

new Vivus("foo", {duration: 100, file: 'bar'}, ()=> myCallback())

If the callback needs to accept an argument

new Vivus("foo", {duration: 100, file: 'bar'}, x=> myCallback(x))

Or if the callback needs to accept a variable number of arguments

new Vivus("foo", {duration: 100, file: 'bar'}, (...args)=> myCallback(...args))

Is that enough options?

^_^


Likewise, I'd recommend removing the binding for this.onScroll in the constructor and where you have this

componentDidMount() {
  document.addEventListener('scroll', this.onScroll);
}

Use this instead

componentDidMount() {
  document.addEventListener('scroll', event=> this.onScroll(event));
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.