CommonJS模块模式

问题描述 投票:2回答:2

我从这里拿走了这个

Flux architecture

var AppDispatcher = require('../dispatcher/AppDispatcher');
var EventEmitter = require('events').EventEmitter;
var TodoConstants = require('../constants/TodoConstants');
var assign = require('object-assign');

var CHANGE_EVENT = 'change';

var _todos = {}; // collection of todo items

/**
 * Create a TODO item.
 * @param {string} text The content of the TODO
 */
function create(text) {
  // Using the current timestamp in place of a real id.
  var id = Date.now();
  _todos[id] = {
    id: id,
    complete: false,
    text: text
  };
}

/**
 * Delete a TODO item.
 * @param {string} id
 */
function destroy(id) {
  delete _todos[id];
}

var TodoStore = assign({}, EventEmitter.prototype, {

  /**
   * Get the entire collection of TODOs.
   * @return {object}
   */
  getAll: function() {
    return _todos;
  },

  emitChange: function() {
    this.emit(CHANGE_EVENT);
  },

  /**
   * @param {function} callback
   */
  addChangeListener: function(callback) {
    this.on(CHANGE_EVENT, callback);
  },

  /**
   * @param {function} callback
   */
  removeChangeListener: function(callback) {
    this.removeListener(CHANGE_EVENT, callback);
  },

  dispatcherIndex: AppDispatcher.register(function(payload) {
    var action = payload.action;
    var text;

    switch(action.actionType) {
      case TodoConstants.TODO_CREATE:
        text = action.text.trim();
        if (text !== '') {
          create(text);
          TodoStore.emitChange();
        }
        break;

      case TodoConstants.TODO_DESTROY:
        destroy(action.id);
        TodoStore.emitChange();
        break;

      // add more cases for other actionTypes, like TODO_UPDATE, etc.
    }

    return true; // No errors. Needed by promise in Dispatcher.
  })

});

在哪里说

上面的代码中有一些重要的事项需要注意。首先,我们维护一个名为_todos的私有数据结构。该对象包含所有单独的待办事项。因为这个变量存在于类之外,但是在模块的闭包内,它仍然是私有的 - 它不能直接从模块外部更改。这有助于我们在不使用操作的情况下更新商店,从而为数据流保留独特的输入/输出接口。

大胆的部分对我来说不清楚。 js解释器如何知道所有这些代码都在模块闭包内,而不是在globals范围内?模块关闭从哪里开始到哪里结束?

我所知道的

用var声明的变量的范围是它的当前执行上下文,它是封闭函数,或者对于在任何函数外部声明的变量,是全局的。

任何解释?

javascript node.js commonjs module-pattern
2个回答
4
投票

你实际上错过了引用的摘录中的最后一行:

module.exports = TodoStore;

CommonJS是一个API,用于定义使用以下约定的模块:

  • 每个文件都定义一个模块,并在隔离的环境中执行;也就是说,它定义的变量不能从模块外部获得。
  • 为了允许导入其他模块,模块可以使用全局变量require,允许它导入其他模块
  • 以同样的方式,变量module可供模块使用,以便它可以设置其exports属性来定义模块应该导出的内容;你在模块a.js中为module.exports设置的值正是require('./a')将返回的值。

实现CommonJS的每个JS环境都必须知道这些规则。当然,这包括Node.js,还有Browserify和Webpack等捆绑包,它们将打包您的代码,以便遵守这些约定。

这样,您就可以控制模块的哪个部分将被导出。

附: :请注意,您还可以使用exports var来定义导出,并且它的使用与module.exports略有不同。有关详细信息,请参阅this StackOverflow question and answer


0
投票

常见的JS模式使用构造函数来定义您的实用程序。

它以类的形式定义。

var moduleName = function() {

  // private variables

  // public functions
  this.method1 = function() {
    // logic1 goes here
  };

  this.method2 = function() {
    // logic2 goes here
  };

};

所以我们将使用将类导出到其他模块

    module.exports = moduleName;

因此,其他模块可以导入它,实例化它然后使用该功能。

如何使用它?

    var module = require('moduleName');  //importing the module created above

这里模块定义被提取,执行,然后在'module'变量中可用。

这个变量名可以是任何名称

    var objectOfModule = new module(); //instance is created

    objectOfModule .method1(); //use1

    console.log(objectOfModule .method2()); //use2

谢谢。

© www.soinside.com 2019 - 2024. All rights reserved.