我从
那里拿走了这个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声明的变量的范围是它的当前执行上下文,它是封闭函数,或者对于在任何函数外部声明的变量的,全局。
有任何解释吗?
答案 0 :(得分:4)
您实际上错过了引用的摘录中的最后一行:
module.exports = TodoStore;
CommonJS是一个API,用于定义使用以下约定的模块:
require
,允许它导入其他模块module
可供模块使用,以便它可以设置其exports
属性来定义模块应导出的内容;您在模块 a.js 中为module.exports
设置的值正是require('./a')
将返回的值。实现CommonJS的每个JS环境都必须知道这些规则。当然,这包括Node.js,还包括Browserify和Webpack等捆绑包,它们将打包您的代码,以便遵守这些约定。
这样,您就可以控制模块的哪个部分将被导出。
P.S。 :请注意,您还可以使用exports
var来定义导出,并且其使用与module.exports
略有不同。有关详细信息,请参阅this StackOverflow question and answer
答案 1 :(得分:0)
Common 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
这里模块定义被提取,执行,然后在'模块中可用。变量
此变量名称可以是任何
var objectOfModule = new module(); //instance is created
objectOfModule .method1(); //use1
console.log(objectOfModule .method2()); //use2
感谢。