最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JS: Return value from EventListener function - Stack Overflow

programmeradmin0浏览0评论

i'm trying to return an array of instances of my Class. However the return is simply returning from the window.addEventListener('load', function(){} ); function I believe. As when I type plugins into the control it is undefined.

;class Parallax {

    constructor(node) {

        // Settings and defaults
        // this.settings = {
        //     container: null,
        //     panels: [],
        //     defaultSpeed: 0.5
        // };

    }

    static initialize() {

        // Ensure DOM has loaded
        window.addEventListener('load', function() {
            // Does page contain any parallax panels?
            let panels = document.querySelectorAll('[data-parallax]');
            if (panels.length > 0) {

                let instances = [];

                // Parallax panels found, create instances of class and return them for reference
                for (const panel in panels) {
                    if (panels.hasOwnProperty(panel)) {
                        instances.push(new this(panels[panel]));
                    }
                }

                return instances;
            } else {
                // Page doesn't appear to have Parallax
                return false;
            }
        }.bind(this));
    }
}
window.plugins = { "parallax-instances": Parallax.initialize() };

Not too sure how to go about doing this, I have tried assigning the window.addEventListener to a variable, however that doesn't return the value. I am retaining the class scope by binding this to my function call within the event listener.

Edit: I did want to start the plugin by simply having the below code, however not too sure how to return possible multiple instances of the class as of course doing the below runs the constructor method first.

window.plugins = { "parallax-instances": new Parallax };

Edit 2 If I return the instances outside of the EventListener I get my desired result. However this could potentially return instances before the page has loaded right?

static initialize() {

        this.instances = [];

        // Ensure DOM has loaded
        window.addEventListener('load', function() {
            // Does page contain any parallax panels?
            let panels = document.querySelectorAll('[data-parallax]');
            if (panels.length > 0) {

                // Parallax panels found, create instances of class and return them for reference
                for (const panel in panels) {
                    if (panels.hasOwnProperty(panel)) {
                        this.instances.push(new this(panels[panel]));
                    }
                }
            }
        }.bind(this));

        return this.instances;
    }

What I get in the console:

{parallax-instances: Array(2)}
    parallax-instances:Array(2)
        0:Parallax {}
        1:Parallax {}
        length:2
    __proto__:Array(0)
    __proto__:Object

i'm trying to return an array of instances of my Class. However the return is simply returning from the window.addEventListener('load', function(){} ); function I believe. As when I type plugins into the control it is undefined.

;class Parallax {

    constructor(node) {

        // Settings and defaults
        // this.settings = {
        //     container: null,
        //     panels: [],
        //     defaultSpeed: 0.5
        // };

    }

    static initialize() {

        // Ensure DOM has loaded
        window.addEventListener('load', function() {
            // Does page contain any parallax panels?
            let panels = document.querySelectorAll('[data-parallax]');
            if (panels.length > 0) {

                let instances = [];

                // Parallax panels found, create instances of class and return them for reference
                for (const panel in panels) {
                    if (panels.hasOwnProperty(panel)) {
                        instances.push(new this(panels[panel]));
                    }
                }

                return instances;
            } else {
                // Page doesn't appear to have Parallax
                return false;
            }
        }.bind(this));
    }
}
window.plugins = { "parallax-instances": Parallax.initialize() };

Not too sure how to go about doing this, I have tried assigning the window.addEventListener to a variable, however that doesn't return the value. I am retaining the class scope by binding this to my function call within the event listener.

Edit: I did want to start the plugin by simply having the below code, however not too sure how to return possible multiple instances of the class as of course doing the below runs the constructor method first.

window.plugins = { "parallax-instances": new Parallax };

Edit 2 If I return the instances outside of the EventListener I get my desired result. However this could potentially return instances before the page has loaded right?

static initialize() {

        this.instances = [];

        // Ensure DOM has loaded
        window.addEventListener('load', function() {
            // Does page contain any parallax panels?
            let panels = document.querySelectorAll('[data-parallax]');
            if (panels.length > 0) {

                // Parallax panels found, create instances of class and return them for reference
                for (const panel in panels) {
                    if (panels.hasOwnProperty(panel)) {
                        this.instances.push(new this(panels[panel]));
                    }
                }
            }
        }.bind(this));

        return this.instances;
    }

What I get in the console:

{parallax-instances: Array(2)}
    parallax-instances:Array(2)
        0:Parallax {}
        1:Parallax {}
        length:2
    __proto__:Array(0)
    __proto__:Object
Share Improve this question edited Nov 16, 2017 at 23:10 Martyn Ball asked Nov 16, 2017 at 22:41 Martyn BallMartyn Ball 4,9059 gold badges63 silver badges145 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

An event listener function is a callback, and runs only when the event happens (in your case, on load).

Callbacks cannot return a value. You could use a variable in the outer scope (e.g. within your class), and reassign it within your event listener.

E.g.

constructor () {
  this.instances = []
}

And then (instead of returning from your event listener):

this.instances = instances

Your initialize is not returning anything. If you elevate instances to outside your event listener and return that, you can remove the other return statements. Note that the returned array will be empty until the callback is actually called (after load).

static initialize() {

    const instances = [];

    window.addEventListener( "load", () => {

        const panels = document.querySelectorAll( "[data-parallax]" );
        for ( let i = 0; i < panels.length; i++ )
            instances.push( new this( panels[ i ] ) );

    });

    return instances;

}

Since you would be returning an array right away, your false syntax would disappear and you'd test .length === 0 instead. You can get the behavior you specified using a getter instead.

发布评论

评论列表(0)

  1. 暂无评论