backbone.js - RequireJS + Backbone + jQuery loaded through `script` interfering with jQuery loaded through RequireJS -
i tried upgrading backbone 1.1.2, , have been having issues jquery.
by default, backbone expects find jquery in base directory ./jquery.js
. when add requirejs path , add shim dependency backbone, works inside of require
, outside, nothing works. it's if local reference creating stomping on globally included jquery?
in html page, have this:
<script src="js/lib/jquery/2.0.2/jquery.min.js"></script> <script src="js/lib/jqueryui/{$jquery.ui.version}/jquery-ui.min.js"></script> <script data-main="js/homepage" src="js/lib/require/2.1.11/require.min.js"></script>
homepage.js
(which works) looks this:
require.config({ baseurl: "./js", paths: { underscore: 'lib/underscore/1.6.0/underscore-min', backbone: 'lib/backbone/1.0.0/backbone-min' // ,jquery: 'lib/jquery/2.0.2/jquery.min' // ,jqueryui: 'lib/jqueryui/1.10.3/jquery-ui.min' }, shim: { // 'jqueryui': { // deps: ['jquery'], // exports: "$" // }, 'underscore': { // deps: ['jquery'], exports: "_" }, 'backbone': { deps: ['underscore', /*'jquery'*/], exports: 'backbone' } } }); require([ 'views/homepage/main' ], function(main) { });
in situation, using global jquery , works perfectly, both inside app, , globally site navigation uses jquery. js minifies r.js
.
but when change bb version 1.1.2, says can't find jquery.js
. when uncomment of lines in homepage.js
include jquery dependencies, renders within application, navigation breaks, saying jquery functions have created undefined. unable minify app in r.js
.
this leads me believe jquery
, $
in global namespace being stomped on when requirejs starts downloading dependencies. classic case of needing use $.noconflict
? if so, how modify code this?
update more recent versions
the answer written backbone 1.1.2, , older version of underscore.
recent versions amd-aware , not need shim
set them. should use lowercase names modules: backbone
, underscore
because of these names hardcoded. (you can work around hardcoding map
config simpler use standard, lowercase names.)
the solution
if load jquery <script>
tag , load in requirejs have take special precautions. however, not notice in question indicates need have 2 jqueries loaded. use following trick use same instance of jquery outside , inside amd modules:
define('jquery', [], function () { return jquery; }); require.config({ baseurl: "./js", paths: { underscore: 'lib/underscore/1.6.0/underscore-min', backbone: 'lib/backbone/1.1.2/backbone-min' }, shim: { underscore: { exports: "_" } } }); require([ 'views/homepage/main' ], function(main) { });
this way when requirejs "loads" jquery
module, it'll execute code passed define
above. recall, jquery ui installs jquery plugin don't need special it. recommend using backbone 1.1.2, not need shim. underscore not depend on jquery shim not need dependency it.
Comments
Post a Comment