Phix
Phix

Reputation: 9880

Dojo scope issue with "inner" require

I'm sure "inner require" isn't the correct term, but it'll make sense here shortly. I'm working on the Dijit tutorials from the toolkit's site, and I'm running into an issue that I think is more a Javascript understanding than a Dojo one.

My page init script:

require(['player', 'dojo/dom', 'ready'], function(Player, dom){
    var p = new Player({
        type : 'video',
        dimensions : [720, 480]
    });
    p.setSource('videos/myvideo.webm')

    p.placeAt(dom.byId('stage') )
})

And my constructor of the dijit "player.js"

constructor : function(opts){
    (function($){
        require(['sg/player/component/Video', 'sg/player/component/Audio'], function(Video, Audio){
            $._setMedia( (opts.type == 'video') ? new Video() : new Audio());
            console.log($._media) // outputs an object "a"
        })
    })(this);
    console.log(this._media) // also outputs the correct object, "a"
}

// the internal setter function used above
_setMedia : function(m){
    this._media = m;
},

(The reason I have an anonymous function there is I don't like assigning var self = this as inside the require blocks, this isn't the containing object.)

When I create the new Player() object in the init script, I can see that a new instance of either Audio or Video is being assigned correctly. However, when I call the p.setSource() in the init script, I get an error that _media is null!

Steps

So my question, hopefully I gave enough context, but why the _media variable losing it's value? Any methods inside the Player instance to be accessed from outside the Dijit's source shouldn't have any effect on the scope of internal variables, but that's what it seems is happening. After the constructor returns, _media should be set! But using

setSource : function(s){
    console.log('Setting source: ', s, this._media)
    // outputs ("Setting source: path/to/video.webm', null)
},

...throws an error as the _media variable it's referencing inside setSource is supposedly null.

Hope that's clear :)

Update

Wish I could give you guys both the checkmark! Thank you for taking the time to help out.

@Frode: There definitely were some async issues that forced me to learn and try more with the structure, all of which failed, leading to this update. I think at some points the files were cached, leading to inconsistent variable content.

@phusick: I hybridized your suggestion which is posted below.

I thought about redoing the structure of how the Player would be instantiated, the object arg and the like, but decided to do the following, in case anyone hits this issue...

I combined the Audio and Video classes into the _Media file, using this structure (code removed for brevity)

define(['dojo/_base/declare'], function(declare){
    var _base = declare("_Media", null, {        
        constructor : function(type){
            this._type = type;
        },
        // etc
    })
    return {
        Video : function(){
            return declare("Video", _base, {
                constructor : function(){
                    this.inherited(arguments, ['video'])
                }
                // etc
            })()
        },
        Audio : function(){
            return declare("Audio", _base, {
                constructor : function(){
                    this.inherited(arguments, ['audio'])
                }
                // etc
            })()
        },
    }
})

...that way there's only one file being loaded initially and it contains both subclasses. Better than loading 2 separate files when one won't be used, IMO.

For the player type instance it then became:

this._media = opts.type && opts.type == 'video' ? new Media.Video() : new Media.Audio();

So far so good! Thanks again.

Upvotes: 1

Views: 553

Answers (2)

phusick
phusick

Reputation: 7352

@Frode is right. Actually, even if the asynchronous operation would be fast enough it won't work, because JavaScript is single-threaded and asynchronous callbacks go into the Event Queue and are executed one after another via Event Loop.

Please see also my answer to Dojo 1.7 how to use dojo components outside of require().

Is there any reason why your player.js does not look like this:

define([
    "sg/player/component/Video",
    "sg/player/component/Audio"
], function(
    Video,
    Audio
) {

    return declare([SomeSuperClass], {

        constructor: function(opts) {
            var media = opts.type && opts.type == "video" ? new Video() : new Audio();
            this._setMedia(media);
        }
    });

});

Upvotes: 1

Frode
Frode

Reputation: 5710

After the constructor returns, _media should be set!

I think this is where you take a wrong step. Keep in mind that require is an asynchronous function!

However, I'm a little confused by this line in your constructor (specifically, the comment):

console.log(this._media) // also outputs the correct object, "a"

Are you 100% sure this outputs "a" and not a null? If you are, please ignore the rest of my answer, because then I've misunderstood something :)

Ok, if you're still reading, I'll try to explain asynchronous require. When you call:

require([".../Video",".../Audio"], function(Video, Audio) {
    // do something and set _media
});

you are basically saying: "Browser, you go fetch the Video and Audio modules for me in the background, while I continue with my next line of code. When you've fetched them, run that function I gave you which sets _media."

In other words, it may take a long time before require() finishes and _media is set, but your code continues right away. So when you call setSource, require() may not be done yet (in fact, it may not even have started downloading anything).

Hope that helps!

Upvotes: 1

Related Questions