我使用一個模塊調用classie.js,它的代碼可以在下面看到:爲什麼在requireJS中會導致「不匹配的匿名定義()」?
/*!
* classie - class helper functions
* from bonzo https://github.com/ded/bonzo
*
* classie.has(elem, 'my-class') -> true/false
* classie.add(elem, 'my-new-class')
* classie.remove(elem, 'my-unwanted-class')
* classie.toggle(elem, 'my-class')
*/
/*jshint browser: true, strict: true, undef: true */
/*global define: false */
(function(window) {
'use strict';
// class helper functions from bonzo https://github.com/ded/bonzo
function classReg(className) {
return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
}
// classList support for class management
// altho to be fair, the api sucks because it won't accept multiple classes at once
var hasClass, addClass, removeClass;
if ('classList' in document.documentElement) {
hasClass = function(elem, c) {
return elem.classList.contains(c);
};
addClass = function(elem, c) {
elem.classList.add(c);
};
removeClass = function(elem, c) {
elem.classList.remove(c);
};
}
else {
hasClass = function(elem, c) {
return classReg(c).test(elem.className);
};
addClass = function(elem, c) {
if (!hasClass(elem, c)) {
elem.className = elem.className + ' ' + c;
}
};
removeClass = function(elem, c) {
elem.className = elem.className.replace(classReg(c), ' ');
};
}
function toggleClass(elem, c) {
var fn = hasClass(elem, c) ? removeClass : addClass;
fn(elem, c);
}
var classie = {
// full names
hasClass: hasClass,
addClass: addClass,
removeClass: removeClass,
toggleClass: toggleClass,
// short names
has: hasClass,
add: addClass,
remove: removeClass,
toggle: toggleClass
};
//transport
if (typeof define === 'function' && define.amd) {
// AMD
define(classie);
} else {
//browser global
window.classie = classie;
}
})(window);
我在HTML寫的:
<script data-main="js/main.js" src="bower_components/requirejs/require.js"></script>
<script src="js/classie.js"></script>
然後,瀏覽器抱怨:
[Error] Error: Mismatched anonymous define() module: [object Object]
http://requirejs.org/docs/errors.html#mismatch
defaultOnError (require.js, line 141)
onError (require.js, line 545)
intakeDefines (require.js, line 1229)
(anonymous function) (require.js, line 1416)
我覺得很奇怪的是classie.js中的最後一行:
//transport
if (typeof define === 'function' && define.amd) {
// AMD
define(classie);
} else {
//browser global
window.classie = classie;
}
看起來像classie.js
會盡可能地保持與AMD
的兼容性,因爲它在使用它之前測試define
是否是一個函數並具有amd
屬性。但不幸的是,這導致了瀏覽器中的錯誤。應該不是requirejs
實現AMD的最着名的庫?爲什麼它不起作用?