Module granularity strategies

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-22 20:45:15

问题


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

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) { ... };

});

Et cetera.

Is either approach preferred? Is there a better approach I'm missing?


回答1:


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.



来源:https://stackoverflow.com/questions/14324123/module-granularity-strategies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!