mm1975
mm1975

Reputation: 1655

Call object function in RequireJS

I use RequireJS to load some scripts.

Now I would like to create some own methods which also needs the loaded script. I've tried a lot but I always get Uncaught (in promise) ReferenceError: hd is not defined. Both scripts are loaded in my index.html.

Calling the method 'connect' from main.js

hd.connect.call(token);

socket-workers.js

...
require.config({

shim: {
    'socket.io': {
      exports: 'io'
    },
    'socket.io-stream': {
      exports: 'ss'
    }
  },
  paths: {
    'socket.io': WEBSOCKET_PROXY_HOST + '/socket.io/socket.io',
    'socket.io-stream': WEBSOCKET_PROXY_HOST + '/socket.io-stream/socket.io-stream'
  },
  waitSeconds: 1

});

requirejs([
  'socket.io', 'socket.io-stream'
], function(io, ss) {

  // Setup Methods & Events

  const hd = {

    connect : function(token) {
      // Connect to Socket, Proxy Server & authenticate
      socket = io(WEBSOCKET_PROXY_HOST, {
        auth: {
          token: token
        }
      }).on('connect', function(data) {
        socketConnected = true;
        isStreaming = false;
        console.log('connected to socket');
        if (activeRecording) {
          //#startRecording();
        }
      });
...

Upvotes: 0

Views: 59

Answers (2)

Damian Dziaduch
Damian Dziaduch

Reputation: 2127

RequireJS can be used this way, but there is a more proper way - define a module and then require it while defining another module:

socket-workers.js:

require.config({

shim: {
    'socket.io': {
      exports: 'io'
    },
    'socket.io-stream': {
      exports: 'ss'
    }
  },
  paths: {
    'socket.io': WEBSOCKET_PROXY_HOST + '/socket.io/socket.io',
    'socket.io-stream': WEBSOCKET_PROXY_HOST + '/socket.io-stream/socket.io-stream'
  },
  waitSeconds: 1

});

define('hd', [
  'socket.io', 'socket.io-stream'
], function(io, ss) {

  // Setup Methods & Events

  const hd = {

    connect : function(token) {
      // Connect to Socket, Proxy Server & authenticate
      socket = io(WEBSOCKET_PROXY_HOST, {
        auth: {
          token: token
        }
      }).on('connect', function(data) {
        socketConnected = true;
        isStreaming = false;
        console.log('connected to socket');
        if (activeRecording) {
          //#startRecording();
        }
      });
    );



    return hd;

main.js:

define(['hd'], function (hd) {
  hd.connect.call(token);
});

Upvotes: 1

mm1975
mm1975

Reputation: 1655

Finally I've found a solution to solve this issue. I've added

window.hd = hd; 

within the function to make the methods available.

Now I can call every method with for e.g. hd.connect(), hd.disconnect()

Upvotes: 0

Related Questions