RequireJS way of creating a copy of object - javascript

Our project is really huge, singe-page enterprise app, based on RequireJS and Backbone.js, and for some complex UI we use jqWidgets.
In particular, these jqWidgets are what is causing us problems.
There are many app features implemented using older jqWidgets 3.3, and for all new ones we would like to use 3.6, but porting old features to 3.6 is very tricky and will cost us time that we don't have at the moment.
What we would like to do to save this time, is having both 3.3 and 3.6 working alongside without creating any problems, and do the porting part later when we can.
What I have tried so far:
requirejs.config({
paths: {
"jquery": "vendor/jquery",
"jqx": "vendor/jqwidgets/3.3",
"jqx3.6": "vendor/jqwidgets/3.6",
... other libs...
},
shim: {
... other shims ...
// jqWidgets3.3
"jqx/jqxcore": {
deps: ["jquery"]
},
"jqx/<<some_plugin>>": {
deps: ["jqx/jqxcore"],
exports: "$.fn.<<some_plugin>>"
},
// jqWidgets3.6
"jqx3.6/jqxcore": {
deps: ["jquery"]
},
"jqx3.6/<<some_plugin>>": {
deps: ["jqx3.6/jqxcore"],
exports: "$.fn.<<some_plugin>>"
},
}
});
Usage in old feature:
require(["jquery", "jqx/<<some_plugin>>"], function($) {
$('<<some_selector>>').<<some_plugin>>(...options...);
});
Usage in new feature:
require(["jquery", "jqx3.6/<<some_plugin>>"], function($) {
$('<<some_selector>>').<<some_plugin>>(...options...);
});
Since both plugins are applied to same jQuery object referencing them with different names/paths works but creates lots of bugs. Example: if first feature you used in app was loaded using jqWidgets 3.3, then next used feature using 3.6 would probably broke, and vice-versa. It only works if you refresh the page after every feature use -- which is kind of pointless since it is single-page app.
So my question is: is it possible to make both jqWidgets 3.3 and 3.6 work alongside by each one of then depend on their own jQuery object so this conflict does not happen?
// Appendix 1:
I think potential solution lies in comment of this question: RequireJS - jQuery plugins with multiple jQuery versions
I'll take a closer look and post here a solution if I find one.

You can use 'map' feature of requirejs,
Map allows you to map the same dependency to different files based on the module which uses dependency.
so you config your build file like this:
requirejs.config({
paths: {
"jquery": "vendor/jquery",
"jqueryForjqx3.6": "toNoConflictJQueryModule",
"jqx": "vendor/jqwidgets/3.3",
"jqx3.6": "vendor/jqwidgets/3.6",
... other libs...
},
map:{
'*':{
.....
},
'jqx':{
'jquery' : 'jquery'
},
'jqx3.6':{
// map jquery to no conlict jquery
'jquery' : 'jqueryForjqx3.6'
},
'jqueryForjqx3.6':{
'jquery' : 'jquery'
}
},
shim: {
... other shims ...
// jqWidgets3.3
"jqx/jqxcore": {
deps: ["jquery"]
},
"jqx/<<some_plugin>>": {
deps: ["jqx/jqxcore"],
exports: "$.fn.<<some_plugin>>"
},
// jqWidgets3.6
"jqx3.6/jqxcore": {
deps: ["jquery"]
},
"jqx3.6/<<some_plugin>>": {
deps: ["jqx3.6/jqxcore"],
exports: "$.fn.<<some_plugin>>"
},
}
});
This configuration maps jquery dependency to different files based on module which uses it.
The content of no conflict version can be like this:
define(['jquery'], function($){
return $.noConflict();
});
You can use http://requirejs.org/docs/jquery.html#noconflictmap about how to use jquery no-conflict and requirejs

if jqWidgets doesn't support it out of the box, I'd try this:
load jQuery
load jqxWidget 3.3
load jQuery again, but in its noConflict mode, and assign it to $2 for instance (I'm not sure RequireJS can do that, but you could copy the jQuery.js file and rename it to something different to load it a second time)
set the 1st jQuery to $1 (window.$1 = $)
set the 2nd jQuery to $ (window.$ = $2)
load jqxWidget 3.6
Now each jqxWidget should have its own, separate jQuery.
Obviously it's not ideal to have jQuery loaded twice, but that shouldn't be a problem apart from using a bit more memory on your app.

Related

RequireJS is loading scripts that are not needed on all pages

Require.js loads every module on every page, so I get JavaScript errors on pages that don't need the loaded scripts. Specifically, the news-filter.js is loading on my search page, and causing the error:
jquery-1.12.3.min.js:2 Uncaught Error: Syntax error, unrecognized expression: "li." from this line in the news-filter.js
$("ul.mediaListing").children("li."+chosenYear).filter("."+chosenCategory).each(function(c) {
Am I missing somthing about how reqire.js determines what scripts are needed on each page?
My main.js file is:
requirejs.config({
baseUrl: [system-view:internal]"/render/file.act?path=/assets/scripts/"[/system-view:internal] [system-view:external]"/assets/scripts/"[/system-view:external],
paths: {
"jquery": "libs/jquery/jquery-1.12.3.min",
"velocity": "libs/velocity/velocity",
"bgstretch": "plugins/background-stretch/background-stretch",
"campus-map": "modules/campus-map",
"velocity-ui": "libs/velocity/velocity.ui",
"slick": "plugins/slick/slick",
"iscroll": "plugins/iscroll/iscroll",
"dotdotdot": "plugins/dotdotdot/jquery.dotdotdot.min.umd",
"select": "plugins/select/select",
"accordion": "modules/accordion",
"news-filter": "modules/news-filter",
"codebird": "modules/codebird",
"social-feed": "modules/social-feed"
},
shim: {
"slick": ["jquery"],
"select": ["jquery"],
"bgstretch": {
deps: ["jquery"]
},
"accordion": ["jquery"],
"codebird": ["jquery"],
"social-feed": {
dep: ["jquery", "codebird"],
exports: "displayFeed"
},
"campus-map": {
deps: [ "jquery" ]
},
"velocity": {
deps: [ "jquery" ]
},
"velocity-ui": {
deps: [ "velocity" ]
}
},
map: {
'*': {
'jQuery': 'jquery'
}
}
});
requirejs(
['jquery', 'modules/utils', 'modules/custom.ui', 'libs/jquery/paginga.jquery', "modules/social-feed", "modules/news-filter"],
function ($, utils, ui, paga, social, news) {
ui();
$(".paginate").paginga({
// use default options
});
});
I like a very modular approach and RequireJS has a lot of different ways to use it. I'll share how I typically have it set up which accomplishes what you are looking for, is streamlined and makes it easy to implement and understand.
I avoid having anything require in my main js completely. First I will create a bundle that includes both the base require.js and a JS file I create called config.js. I will have this bundle loaded in my layout page so it's always available. If you aren't using MVC, the idea is just to make sure Require and my custom config file are always loaded together and always available so do what you need to for that.
Config.js is very simple, in your case just taking your code it will look like this:
var require = {
baseUrl: [system-view:internal]"/render/file.act?path=/assets/scripts/"
[/system-view:internal] [system-view:external]"/assets/scripts/"[/system-
view:external],
paths: {
"jquery": "libs/jquery/jquery-1.12.3.min",
"velocity": "libs/velocity/velocity",
"bgstretch": "plugins/background-stretch/background-stretch",
"campus-map": "modules/campus-map",
"velocity-ui": "libs/velocity/velocity.ui",
"slick": "plugins/slick/slick",
"iscroll": "plugins/iscroll/iscroll",
"dotdotdot": "plugins/dotdotdot/jquery.dotdotdot.min.umd",
"select": "plugins/select/select",
"accordion": "modules/accordion",
"news-filter": "modules/news-filter",
"codebird": "modules/codebird",
"social-feed": "modules/social-feed"
},
shim: {
"slick": ["jquery"],
"select": ["jquery"],
"bgstretch": {
deps: ["jquery"]
},
"accordion": ["jquery"],
"codebird": ["jquery"],
"social-feed": {
dep: ["jquery", "codebird"],
exports: "displayFeed"
},
"campus-map": {
deps: [ "jquery" ]
},
"velocity": {
deps: [ "jquery" ]
},
"velocity-ui": {
deps: [ "velocity" ]
}
},
map: {
'*': {
'jQuery': 'jquery'
}
}
};
That's it. I tend to have all of my javascript files associated to each HTML page separated, so in the paths section of the set up I'll have the view name and then the location in my source of the corresponding javascript file. Then in my HTML page when I'm adding in scripts, I'll simply state
<script> require(['sign-in']); </script>
This will grab the script file I have defined in the require variable for my view. Then in each script file, sign-in.js for example for this one, I will wrap all of the scrip in a define statement, so at the top of each JS file you can clearly see what dependencies you will load and use in that page. It's clean, it's a framework, it works wonderfully, and it keeps you from loading things you don't need.
In the self contained JS file you would do:
define(['jquery', 'lodash', 'bootstrap'], function ($, _) {
//All JS code here
}):
I will have all my libraries that need a selector defined first and then everything else after. That's it, hopefully a real example will help you.
Am I missing somthing about how reqire.js determines what scripts are needed on each page?
Sure looks like you are. You show a main.js file that has this (reformatted to help readability):
requirejs(['jquery', 'modules/utils', 'modules/custom.ui',
'libs/jquery/paginga.jquery', "modules/social-feed",
"modules/news-filter"],
If you use this main.js on all your pages, then all the modules you list there are going to be loaded, which means that modules/news-filter is going to be loaded on all pages. This, irrespective of whether any code actually uses it.
The way RequireJS works, any dependency listed in a require call is loaded. And for each module loaded, any dependency they list in their define call or in a shim set for them in your configuration is also loaded. It does not matter one bit if something is listed but not actually used by your code.
Tangential remark about your configuration. In your paths you have:
"news-filter": "modules/news-filter"
But then you refer to it as modules/news-filter in your require call instead of news-filters. You should use news-filter or remove the mapping you've set in paths. RequireJS does now allow referring to the same JavaScript file through two different module names in the same context. If you load your module as modules/news-filter in one place and as news-filter somewhere else, you're going to run into problems.
If you need to use two different names to access the same JavaScript file, you use map. What map does is tell RequireJS "when you get a request for module X, load module Y instead". So RequireJS replaces the module name requested with a different one.

Load textext.js plugin with require.js

I'm trying to load textext.js jquery plugin, with one of it's plugins, textext tags. On my project, I'm using require.js in order to load all scripts with it's dependencies.
As used for other scripts, I'm using a shim config on my main.js file:
main.js
require.config({
shin: {
jquery: {
exports: '$'
},
'textext': {
deps: ['jquery'],
exports: '$.fn.textext'
},
'textext_tags': {
deps: ['jquery', 'textext'],
}
},
paths: {
jquery: 'lib/jquery-min',
textext: 'lib/textext/textext.core',
textext_tags: 'lib/textext/textext.plugin.tags',
}
});
On the page that I use it, I call it as above:
file-app.js
define([
'jquery',
'textext',
'textext_tags',
], function($, Textext, TextextTags) {
// do stuff
});
The code is loading and working correctly on firefox, but on Chromium, sometimes (about 2/3 of the times), at the first time that I load the page, I've receive the following error, that broke the functioning of the page:
TypeError: Cannot set property 'TextExtTags' of undefined
#3 localhost/js/lib/textext/textext.plugin.tags.js:23:27
Inside the file textext.plugins.tags.js, we have at line 23 (the failure line):
$.fn.textext.TextExtTags = TextExtTags;
So, inspecting it with Firebug, I realize that Jquery is not loaded, so $ and $.fn is undefined.
My question is: why this schema of require.js is working with other jQuery plugins on the same project (like jquery cookie and others), but not with this, a jquery plugin with it's subplugins?
As Vishwanath said, only changing from "shin" to "shim" worked, like above:
require.config({
shim: {
jquery: {
exports: '$'
},
...
Thanks!

Include jQuery UI with requireJS using noConflict jQuery

I'm working on a JavaScript module that uses jQuery, some functions of jQuery UI (draggable) and jPlayer. Recently I made myself familiar with requireJS to manage the dependencies properly.
I don't want to produce conflicts with a possibly already existing jQuery version that the site that includes my script uses. For this reason I am mapping the jQuery dependencies to a module "jquery-private" with a call of noConflict(), as is described in the requireJS guide.
As jQuery UI takes up a lot of space, I would also like to just include the modules that I am actually using. ui.draggable has the dependencies ui.core, ui.mouse and ui.widget, so I should have to include these 4 modules.
My problem is that I would like the jQuery UI modules and the jPlayer module to use my own version of jQuery, but obviously it isn't accessible by the global $ variable after I called the noConflict() method. Unfortunately neither jQuery UI nor jPlayer are AMD modules, so I needed to make shim configurations for them.
Here is my definition of the dependencies:
require.config({
baseUrl: 'javascript/modules',
paths: {
jquery: 'jquery-2.1.3',
jPlayer: 'jquery.jplayer',
uiCore: 'jquery.ui.core',
uiMouse: 'jquery.ui.mouse',
uiWidget: 'jquery.ui.widget',
uiDraggable: 'jquery.ui.draggable'
},
map: {
// '*' means all modules will get 'jquery-private'
// for their 'jquery' dependency.
'*': { 'jquery': 'jquery-private' },
// 'jquery-private' wants the real jQuery module
// though. If this line was not here, there would
// be an unresolvable cyclic dependency.
'jquery-private': { 'jquery': 'jquery' }
},
shim: {
jPlayer: {
deps: ['jquery']
},
uiCore: {
deps: ['jquery']
},
uiMouse: {
deps: ['jquery','uiCore']
},
uiWidget: {
deps: ['jquery','uiCore']
},
uiDraggable: {
deps: ['jquery','uiCore','uiMouse','uiWidget']
}
}
});
require(["json","jquery","jPlayer","uiDraggable"], function(json,___jQuery,jplayer,uiDraggable) {
(...)
}
Obviously this code produces errors as the $ variable in the jQuery UI modules is not defined.
Is there any way to pass my own jQuery object to modules? The top answer in another thread (How use require.js to load jQuery with noConflict) suggests that what I am trying to do is not possible, but maybe there is some other way to do it?
If there is none, I probably have to use global variables and heavily edit the included modules, which kind of makes it questionnable why to use a dependency management library like requireJS in the first place...
I found the following code on top of each module in jquery.ui:
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define([ "jquery" ], factory );
} else {
// Browser globals
factory( jQuery );
}
}(function( $ ) {...});
And it means jquery.ui checks when global AMD "define" function is defined and uses 'jquery' as AMD reference for module.
It will use no conflict of jquery based on requirejs recommendation in this and this.
And about how to use jQuery with AMD.

Scripts Dependencies Using RequireJS Shim

I'm upgrading from jQuery 1.8 to 1.9 and since jQuery.browser() is removed, I will use jQuery Browser Plugin.
My requirejs config file (loaded using data-main="") looks somewhat like this:
(EDITED - added more code snippets)
main-comp.js
require.config({
paths: {
jquery: 'libs/jquery/jquery1.9.1.min',
utils: 'modules/utils',
myController: "controllers/myController",
browserPlugin: 'libs/jquery/jquery.browser.min'
},
shim: {
browserPlugin: {
deps: ['jquery']
}
}
});
require(['myController', 'jquery'], function (controller, $) {
$(controller.start);
}
);
moduls/utils.js
define(['browserPlugin'], function () {
return {
browser: $.browser
};
});
myController.js
define(['utils'], function (utils) {
function start() {
console.log(utils.browser.msie)
}
return {
start: start
};
});
Everything seemed to work properly, but then I saw that sometimes in IE only I get a 'jQuery' is undefined (it's a capital Q there) or '$' is undefined errors from the jquery.browser.min.js file.
I thought the deps means that jquery will load before the jquery.browser file but apparently this isn't always the case. I tried following this answer and add exports: "$.fn.browser" but with no success.
When running an optimized version (minify+uglify using r.js) I haven't encountered it.
What am I doing wrong?
You need to ensure you reference $ as a parameter in the require callback. Like so:
require(['myController', 'jquery'], function (controller, $) {
$(controller.start);
}
);
This ensures that jQuery is available to use. It is a bit of an odd one as it will expose itself globally anyway so it will sometimes work regardless, but the correct way is to explicitly require it and use it inside the callback as a parameter.
It looks like you are missing jquery dependency in moduls/utils.js, please try:
define(['jquery', 'browserPlugin'], function ($) {
return {
browser: $.browser
};
});
and also, just to be on the safe side, add jquery to your shim :
jquery: {
exports: "$"
},
By the way, why don't you use $.browser in your code and just load the jquery plugin using the shim configuration?
I had the same problem, the script in data-main is loading asynchronously, that means that it may load after the scripts it defines.
The solution is to load another script with the require.config right after the require.js script.
data-main Entry Point Documentation.

How to debug a 3rd party library when moving to requirejs

I moved a project to requirejs and everything works fine except for a detail with a 3rd party library (which is not an AMD module). I would like to know any suggestions on the techniques to follow to resolve these type of issues when using requirejs.
The 3rd party library is kendo-ui and the issue is when trying to change the locale by calling kendo.culture("es-MX"). The function is being called without an error but it does not work as supposed.
The way to use this is kendo is by:
loading kendo :
loading the locale :
calling the function: kendo.culture("es-MX");
I checked and the only global variable that gets exported is named kendo by the kendo script. I cannot see any global variable added by kendo.culture.es-MX.min.js
The setup I did in my main script for requirejs is:
require.config({
paths: {
jquery: 'lib/jquery-1.7.2.min',
signals: 'lib/signals',
hasher: 'lib/hasher',
crossroads: 'lib/crossroads',
kendo: 'lib/kendo.web.min',
kendoCulture: 'lib/cultures/kendo.culture.es-MX.min',
knockout: 'lib/knockout-2.1.0',
knockout_kendo: 'lib/knockout-kendo.min',
underscore: 'lib/underscore-min',
json2: 'lib/json2',
faclptController: 'faclpt/faclptController',
FacturaViewModel: 'faclpt/FacturaViewModel',
ConfigViewModel: 'faclpt/ConfigViewModel',
domReady: 'lib/domReady'
},
shim: {
'kendoCulture': {
deps: ['kendo']
},
'kendo' : {
exports: 'kendo'
}
}
});
require([
'require',
'jquery',
'knockout',
'knockout_kendo',
'underscore',
'json2',
'faclptController',
'FacturaViewModel',
'ConfigViewModel',
'domReady'
], function (
require,
$,
ko,
knockout_kendo,
_,
json2,
faclptController,
FacturaViewModel,
ConfigViewModel,
domReady) {
// Start of Main Function
domReady(function () {
kendo.culture("es-MX");
// knockout Bindings
ko.applyBindings(FacturaViewModel, document.getElementById('Proceso'));
ko.applyBindings(ConfigViewModel, document.getElementById('Configuracion'));
});
});
So what else should I look for?
I would appreciate any techniques or tips on how to debug requirejs

Categories