我构建了一个我需要在 BackboneJS 项目中使用的小型 javascript 库。 我的问题是,我在使用图书馆时遇到问题。我想我做错了什么,当我试图访问它时,我得到了一个“未定义”。
下面的一些代码,我简化了它。
图书馆看起来像那样 - myLibrary.js:
(function() {
var myLibrary = this;
var initialize = function() {
console.log('initialize');
};
myLibrary.otherFunction = function() {
console.log('otherFunction');
};
return myLibrary;
})();
我将我的库放在我的 requirejs 配置中:
requirejs.config({
paths: {
jquery: "js/jquery"
myLibrary: "js/myLibrary"
},
shim: {
myLibrary: {
deps: ['jquery']
}
}
});
我正在尝试在 BackboneJS View 中使用我的库
define([
'jquery',
'backbone',
'myLibrary'
], function($, Backbone, myLibrary){
'use strict';
return Backbone.View.extend({
initialize: function() {
console.log(myLibrary);
//myLibrary is undefined here!
//I'd like to access myLibrary as an object
//to access my functions inside..
}
});
});
库已加载。我可以在开发者栏的“网络”选项卡中看到它。
如果你知道这里出了什么问题?
谢谢。
最佳答案
按照您现在的方式,您的 myLibrary
脚本实际上正在运行,但是返回值 (return myLibrary;
) 正在被丢弃,因为它没有被分配给任何东西。您可以执行以下两项操作之一:
您可以将返回值分配给全局对象上的某些内容并更新您的 shim
配置:
window.myLibrary = (function() {
var myLibrary = this;
var initialize = function() {
console.log('initialize');
};
myLibrary.otherFunction = function() {
console.log('otherFunction');
};
return myLibrary;
})();
requirejs.config({
paths: {
jquery: "js/jquery"
myLibrary: "js/myLibrary"
},
shim: {
myLibrary: {
deps: ['jquery'],
exports: "myLibrary"
}
}
});
或者,更好的是,在您的库中实际使用 define
:
define(["jquery"], function ($) {
var myLibrary = this;
var initialize = function() {
console.log('initialize');
};
myLibrary.otherFunction = function() {
console.log('otherFunction');
};
return myLibrary;
});
关于javascript - 使用 RequireJS 加载外部 javascript 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18004294/