RequireJS:如何定义构造函数? [英] RequireJS: How to define a constructor?
问题描述
我想根据AMD规范创建构造函数.我找到了此答案,并尝试遵循它.这就是我最终得到的:
I want to create constructors according to the AMD specification. I found this answer and tried to follow it. Here's what I ended up with:
requirejs.config({
paths: {
'jquery': 'vendor/jquery-1.9.1.min',
'lodash': 'vendor/lodash-1.3.1.min',
'knockout': 'vendor/knockout-2.2.1.min',
'bootstrap': 'vendor/bootstrap-2.3.2.min'
}
});
requirejs(
['jquery', 'lodash', 'knockout', 'controller/categories'],
function main($,_,ko, CategoriesCtrl) {
var categories = new CategoriesCtrl();
}
);
controller/categories.js
define('categories', function() {
return function CategoriesCtrl(layers) {
var self = this;
layers = layers || [];
console.log(ko);
};
});
我得到的结果是CategoriesCtrl是未定义的.我做错了什么?
The result I get is that CategoriesCtrl is undefined. What have I done wrong?
推荐答案
您已创建一个名为AMD模块,方法是将您的第一个参数设为define
'categories'
.最好在可能的情况下避免这种情况:
You have created a named AMD module by making your first argument to define
'categories'
. It's best to avoid this where possible:
您可以自己显式命名模块,但这会使模块 便携式性较差-如果将文件移动到另一个目录,您将 需要更改名称.通常最好避免使用名称编码 的模块,然后让优化工具在模块中刻录 名称.
You can explicitly name modules yourself, but it makes the modules less portable -- if you move the file to another directory you will need to change the name. It is normally best to avoid coding in a name for the module and just let the optimization tool burn in the module names.
尝试将categories.js
调整为此:
define(function() {
return function CategoriesCtrl(layers) {
// etc
};
});
这篇关于RequireJS:如何定义构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!