问题描述
我有三个页面(这是单页界面)的应用程序。该网页有相似但不完全相同的功能。
I have an application with three pages (which are single-page interfaces). The pages have similar but not identical functionality.
所以,我想有JavaScript的模块,提供了常用的功能。然后,每个页面可以自定义/覆盖的通用功能的部分。
So I want to have javascript-modules that provide the common functionality. Then each page may customize/overwrite parts of the common functionality.
我使用Backbone.js的,所以我做的是:
I'm using backbone.js, so what I do is:
- 加载包含常见的模型文件,浏览,收藏等。
- 加载应用程序特定的文件定义的步骤1 /覆盖部分
- 调用instanciates所有必要的模型/查看/收藏的init()函数
目前,我存储我的模块,类似于这样一个模块容器:。所以:
As discussed in the comments above, you can avoid having to explicitly reference the parameters of the function by looping over them using the arguments
object inside the function body. So:
require(['module1', 'module2', 'module3', ..., 'moduleN'],
function(module1, module2, module3, ..., moduleN) {
var init = function() {
module1.init();
module2.init();
module3.init();
...
moduleN.init();
};
return {init: init};
});
变成了:
require(['module1', 'module2', 'module3', ..., 'moduleN'],
function() {
var args = arguments;
var init = function() {
var module;
for (module in args) {
if (args.hasOwnProperty(module) && typeof module.init === 'function') {
module.init.call(this);
}
}
};
return {init: init};
});
我在的hasOwnProperty加()
检查里面的在
循环,因为,对于一些原因,这是。此外,您会看到的init
明确检查试图调用它之前是一个功能。
I added in a hasOwnProperty()
check inside the for in
loop because, for a number of reasons, it's good practice. Also, you'll see the explicit check for init
being a function before attempting to call it.
原因变参=参数
是这样你就可以从内部函数引用它 - 否则你会被引用传递给初始化参数()
,这是不是你想要的。
The reason for var args = arguments
is so you can reference it from the inner function - otherwise you would be referencing the arguments passed to init()
, which is not what you want.
由于和一边,在一个建筑的水平,我想你所描述的项目结构的成效斐然, - 我把它用在了很多非常大的项目,它从来没有让我失望。 Require.js是真棒! :)
As and aside, on an architectural level, I think the project structure you've described works incredibly well - I use it on a lot of very big projects and it's never let me down. Require.js is awesome! :)
这篇关于require.js + Backbone.js的:如何构建有一个初始化功能模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!