简体   繁体   English

在RequireJS中的Require中使用Require

[英]Using Require Within Define in RequireJS

Is it possible to use require within a define block? 是否可以在定义块中使用require?

I am trying to load the facebook JS API but need to wrap it in a require with a different context because I don't want the whole application to stop loading if Facebook is blocked by a firewall. 我正在尝试加载facebook JS API,但需要将其包装在具有不同上下文的require中,因为如果Facebook被防火墙阻止,我不希望整个应用程序停止加载。

The problem I have is how to return the module from within the nested require() call. 我的问题是如何从嵌套的require()调用中返回模块。

My code looks something like this: 我的代码如下所示:

define( [ 'require' ], 
    function( require ) 
{
    var fbRequire = require( 
    { 
        context: 'fb',
        waitSeconds: 3
    } );

    fbRequire.onError = function()
    {
        console.warn( 'fbRequire.onError', arguments );
    };

    fbRequire( [ 'https://connect.facebook.net/en_US/all/debug.js' ], 
        function() 
    {
        console.log( 'facebook file now loaded' );

        // init the Facebook JS SDK
        var facebookSettings = {
            channelUrl: '//' + window.location.hostname + '/facebook-channel.html', // Channel File for x-domain communication
            status: true, 
            cookie: true, 
            xfbml: true,
            appId: '1234567890'
        };

        FB.init( facebookSettings );

        // this is the bit I'm confused about
        // how do I...
        return FB;
        // ...because it's asynchronous and needs to be returned from the define() call?
    } );
} );

This is a Dojo project, if that helps (do I need to use dojo/Deferred?). 这是一个Dojo项目,如果有帮助的话(我需要使用dojo / Deferred吗?)。

I have solved the problem but couldn't get the Dojo loader to not fallover when Facebook was blocked. 我已经解决了问题,但是在Facebook被阻止时无法使Dojo加载程序不发生故障转移。 Instead, I used straight JS to load the SDK. 相反,我使用了简单的JS来加载SDK。 Hopefully this will help someone else. 希望这会帮助其他人。

define( [ 'require' ], 
    function( require ) 
    {
        return {
            /**
             * Loads a facebook asynchronously using require() and a "bang" (!).
             * 
             * @example require( ['my-project/facebookLoader!'],    function( facebook ) { ... } );
             */
            load: function( store, require, callback )
            {
                // already loaded?
                if( window.FB !== undefined )
                {
                    console.log( 'facebook already loaded - using global FB object.' );
                    callback( window.FB );
                }
                else
                {
                    require( [ 'dojo/dom-construct', 
                        'dojo/_base/window', 
                        'dojo/on',
                        'dojo/_base/event' ], // remove "/debug" in live env
                    function( domConstruct, win, on, event ) 
                    {
                        // add Facebook div
                        domConstruct.create( 'div', { id:'fb-root' }, win.body(), 'first' );

                        // init the Facebook JS SDK
                        var facebookSettings = {
                            channelUrl: '//' + window.location.hostname + '/facebook-channel.html', // Channel File for x-domain communication
                            status: false, // check the login status upon init?
                            cookie: true, // set sessions cookies to allow your server to access the session?
                            xfbml: false    // parse XFBML tags on this page?
                        };

                        // app ID from the App Dashboard
                        if( window.location.hostname == 'localhost' )
                        {
                            facebookSettings.appId = '123456788'; 
                        }
                        else
                        {
                            facebookSettings.appId = '123456789'; 
                        }

                        // what do we do if Facebook is blocked or times out?
                        var loadFailed = function( errorEvent )
                        {
                            console.warn( 'Facebook failed to load. Some features will be unavailable. ' + ( errorEvent ? 'Script error.' : 'Timed out.' ) );

                            // scrap the timer (in case we got here from error event on script tag)
                            if( timerId )
                            {
                                window.clearTimeout( timerId );
                            }

                            if( errorEvent !== undefined )
                            {
                                event.stop( errorEvent );
                            }

                            window.fbAsyncInit = function(){}; // noop

                            // return fake Facebook object
                            callback( 
                            { 
                                getLoginStatus: function()
                                {
                                    return false;
                                }
                            } );

                        };

                        // give Facebook 5 seconds to load
                        var timerId = window.setTimeout( loadFailed, 5000 );

                        // hook into Facebook's load callback
                        window.fbAsyncInit = function() 
                        {
                            window.clearTimeout( timerId );
                            FB.init( facebookSettings );
                            callback(  window.FB );
                        };

                        // Load the SDK Asynchronously
                        ( function(d)
                        {
                            var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
                            if (d.getElementById(id)) {return;}
                            js = d.createElement('script'); js.id = id; js.async = true;
                            js.src = "//connect.facebook.net/en_US/all/debug.js"; // dev version
                            //js.src = "//connect.facebook.net/en_US/all.js"; // production version
                            on( js, 'error', loadFailed );
                            ref.parentNode.insertBefore(js, ref);
                        }( document ) );

                    } );
                }
            }
        };
    } 
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM