模块粒度策略 [英] Module granularity strategies
问题描述
我正在使用RequireJS构建KnockoutJS网络应用程序以对其进行模块化.我正在尝试将几种方法分解为模块的策略.
I'm building a KnockoutJS web app using RequireJS to modularize it. I'm trying to decide between a couple of strategies to break things into modules.
扁平化方法:
一种方法具有更平坦的目录结构和更大的模块:
Flat approach:
One approach features a flatter directory structure and larger modules:
/webapp
|-/scripts
|-/templates
| |-car_edit.html
| |-car-view.html
| |-person_edit.html
| |-person_view.html
|-main.js
|-person.js
|-car.js
例如,person模块(在person.js中)的实现方式如下:
As an example, the person module (in person.js) is implemented something like this:
define(['jquery', 'knockout', ...], function($, ko, ...) {
var PersonViewModel = function PersonViewModel() { ... };
var load = function load(id) { ... };
var create = function create() { ... };
var view = function view(element, model) { ... };
var edit = function edit(element, model) { ... };
return {
Model : PersonViewModel, // exposes ViewModel for testing
create : create, // reserve id on server, return new empty Person
load : load, // get data from server, return new Person w/ data
view : view, // load view template, bind Person
edit : edit // load edit template, bind Person
};
});
深层结构方法:
另一种方法是使用具有较小模块的更深目录结构:
Deep structure approach:
Another approach would use a deeper directory structure with smaller modules:
/webapp
|-/scripts
|-/car
| |-/templates
| | |-edit.html
| | |-view.html
| |- Model.js
| |- view.js
| |- edit.js
| |- create.js
| |- load.js
|-/person
| |-/templates
| | |-edit.html
| | |-view.html
| |- Model.js
| |- view.js
| |- edit.js
| |- create.js
| |- load.js
|-main.js
代码与之前的示例相似,不同之处在于模块的每个部分现在都是其自己的模块:
The code is similar to the example before, except each part of the module is now it's own module:
// /person/Model.js
define(['jquery', 'knockout', ...], function($, ko, ...) {
return function Model() { ... };
});
// /person/view.js:
define(['jquery', 'knockout', ...], function($, ko, ...) {
return function view(element, model) { ... };
});
等等.
哪种方法更可取?有什么更好的方法我想念吗?
Is either approach preferred? Is there a better approach I'm missing?
推荐答案
对于Backbone/Require,我们正在使用这个样板,我认为您可以将其与其他框架一起使用,而无需花费太多精力.
With Backbone/Require we are using this Boilerplate, I think you can use it with another framework with small adjusment.
它非常完整,即使您是第一次找到代码,也很容易找到一个模块.
It is very complete, and it is very easy to find a module, even if you find the code for the first time.
这篇关于模块粒度策略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!