rquirejs - getting issue from global space - javascript

In my app, I created a global space for my app saying socialApp. even before i call the initialize method, I am declaring the socialApp in the window like this:
define([
'jquery',
'underscore',
'backbone',
'marionette',
'scripts/appRoutes',
'scripts/app/appModel',
'scripts/app/layout/appLayout'],
function ($,_,Backbone,Marionette,Routes,appModel,appLayout) {
"use strict";
socialApp = window.socialApp || {}; // i am declared the socialApp here.
socialApp = new Backbone.Marionette.Application();
socialApp.addInitializer(function(options) {
socialApp.NewRoute = new Routes;
socialApp.GenModel = new appModel({router:socialApp.NewRoute}); //i am getting error saying "Uncaught ReferenceError: socialApp is not defined" - why?
socialApp.Layout = new appLayout();
socialApp.Layout.render();
Backbone.history.start();
});
It is not happening always, but some instance i am getting this error. how to resolve this?
in the appModel i declared like this :
define(['jquery','underscore','backbone','marionette'],
function ($,_,Backbone,Marionette) {
"use strict";
socialApp = window.socialApp || {}; //exactly i am getting error from here on refresh some times..
socialApp.Model = Backbone.Model.extend({
initialize:function(currentRoute){
this.router = currentRoute.router;
}
});
return socialApp.Model;
});
Where i do the mistake? any one figure out me please?

You can't declare global variable within an AMD module like that, socialApp is a local variable within the module itself. So either declare an AMD module for your socialApp variable like this:
File: socialApp.js
define(['marionette'], function(Marionette) {
var socialApp = {};
return socialApp;
});
And require socialApp from everywhere you use it.
File: appModel.js
define(['jquery','underscore','backbone','marionette', 'socialApp'],
function ($,_,Backbone,Marionette, socialApp) {
socialApp.Model = Backbone.Model.extend({
initialize:function(currentRoute){
this.router = currentRoute.router;
}
});
return socialApp.Model;
});
Or, if you insist on global variables; declare socialApp within window explicitly.
replace socialApp = window.socialApp || {}; with window.socialApp = window.socialApp || {};.

Related

Expose AMD module globally when not in a RequireJS environment

I am attempting to convert a classic JavaScript "class" into an AMD module. However, I also need to keep exporting the class into the global namespace because some legacy code needs it. I've tried this, however, the global object is not created. What am I doing wrong?
define('VisitorManager', function () {
var VisitorManager = function () {
"use strict";
// ...
};
VisitorManager.prototype.hasExistingChat = function () {
// ...
};
//expose globally
this.VisitorManager = VisitorManager;
//return AMD module
return VisitorManager;
});
To expose your module globally, you need to register it in the global object.
In the browser the global object is window:
window.VisitorManager = VisitorManager;
In a Node.js environment the global object is called GLOBAL:
GLOBAL.VisitorManager = VisitorManager;
To use the class in both a legacy environment and with RequireJS, you can use this trick:
(function() {
var module = function() {
var VisitorManager = function() {
"use strict";
// ...
};
// Return the class as an AMD module.
return VisitorManager;
};
if (typeof define === "function" && typeof require === "function") {
// If we are in a RequireJS environment, register the module.
define('VisitorManager', module);
} else {
// Otherwise, register it globally.
// This registers the class itself:
window.VisitorManager = module();
// If you want to great a global *instance* of the class, use this:
// window.VisitorManager = new (module())();
}
})();

ReferenceError: ProductStore is not defined

I'm trying to migrate some old javascript / backbone code over to our new system and I'm running into the following error.
ReferenceError: ProductStore is not defined
ProductStore.Options = {},
ReferenceError: ProductStore is not defined
ProductStore.type= "board";
My JS file looks like this.
ProductStore.Options= {},
function() {
"use strict", ProductStore.Options.Product = Backbone.Model.extend({
//do something
})
}(),
function() {
"use strict", ProductStore.Options.ProductView = Backbone.View.extend({
//do something
})
}()
There is no other js files, so I'm wondering what I'm doing wrong?
Error says it all, you can't say:
ProductStore.options = {}
unless you have already declared ProductStore (and defined it to be an object).
e.g.
var ProductStore = {};
You have to create a ProductStore JS object first:
var ProductStore = {};
You have to change your , with ;
var ProductStore = {};
Not sure but best practice is to declare object is to make it fail safe. Someone told me the same in one of my project.
var ProductStore = ProductStore || {};

How to solve circular dependency in Require.js?

Basically, the idea is that "sub" module creates an object, and that object should be part of a utilities library which is the "main" module. However, the "sub" object depends on utilities from "main":
// Main module
define(['sub'], function(sub) {
var utils = {
utilityMain: function () {
// ...
};
// ...
};
tools.subModule = sub;
return tools;
});
// Sub module
define(['main'], function(main) {
return new (function () {
// Singleton object using functions in main module
var somestuff = function () {
main.utilityMain();
// etc
};
})();
});
How can I achieve this with require.js without creating a black hole that would swallow the whole planet?
Thank you very much.
There are a few things suggested in the docs:
b can fetch a later after modules have been defined by using the require() method (be sure to specify require as a dependency so the right context is used to look up a)
e.g.:
// Sub module
define(['require'], function(require) {
return new (function () {
// Singleton object using functions in main module
var somestuff = function () {
require('main').utilityMain();
// etc
};
})();
});
or
you could instead use exports to create an empty object for the module that is available immediately for reference by other modules
e.g.:
// Main module
define(['sub', 'exports'], function(sub, exports) {
exports.utilityMain: function () {
// ...
};
exports.subModule = sub.sub;
});
// Sub module
define(['main', 'exports'], function(main, exports) {
exports.sub = new (function () {
// Singleton object using functions in main module
var somestuff = function () {
main.utilityMain();
// etc
};
})();
});
and
Circular dependencies are rare, and usually a sign that you might want to rethink the design

logging javascript module names

I want to be able to log my module initializations to see what happens. Is there a way to get the module namespace and log it to the console.
(function($, bis, window, document, undefined) {
"use strict";
//other app code
bis.library = bis.library || function(module) {
$(function() {
if (module.init) {
module.init();
//how can I make it log the module namespace
console.log('module' + module.toString() + 'initialized');
}
});
return module;
};
//other app code
})(jQuery, window._bis = window._bis || {}, window, document);
example of my module definition
(function($, bis, window, document, undefined) {
"use strict";
var common = bis.common,
urls = bis.urls,
defaults = bis.defaults,
createWorklist = bis.createWorklist,
editWorklist = bis.editWorklist,
editMoveBoxesWorklist = bis.editMoveBoxesWorklist;
bis.worklist = bis.worklist || bis.library((function() {
// module variables
var init = function() {
//module init code
};
//other module code
return {
init: init
};
})());
})(jQuery, window._bis = window._bis || {}, window, document);​
So I want the line console.log to log the following text "module bis.worklist initialized" for example.
I did as Pointy suggested. I have added a name property to my modules and just use the
console.log(module.name);

Express.JS not recognizing required js file's functions

Even though, I've imported the JS file that includes the function that I will use, Node.JS says that it is undefined.
require('./game_core.js');
Users/dasdasd/Developer/optionalassignment/games.js:28
thegame.gamecore = new game_core( thegame );
^
ReferenceError: game_core is not defined
Do you have any idea what's wrong? Game_core includes the function:
var game_core = function(game_instance){....};
Add to the end of game_core.js:
module.exports = {
game_core : game_core
}
to games.js:
var game_core = require('./game_core').game_core(game_istance);
Requiring a module in Node doesn't add its contents to the global scope. Every module is wrapped in its own scope, so you have to export public names:
// game_core.js
module.exports = function (game_instance){...};
Then keep a reference in your main script to the exported object:
var game_core = require('./game_core.js');
...
thegame.gamecore = new game_core( thegame );
You can read more about it in the docs: http://nodejs.org/api/modules.html#modules_modules
An alternative approach:
if( 'undefined' != typeof global ) {
module.exports = global.game_core = game_core;
}

Categories

Resources