HTML and CSS Reference
In-Depth Information
14.2 The Controller
For any request to the /comet URL, the server will call the controller's create
method, passing it request and response objects. It then proceeds to call a method
on the resulting controller corresponding to the HTTP method used. In this chapter
we will only implement the get and post methods.
14.2.1 CommonJS Modules
Node implements CommonJS modules, a structured way to manage reusable
JavaScript components. Unlike script files loaded in browsers, the implicit scope in
modules is not the global scope. This means that we don't need to wrap everything
in anonymous closures to avoid leaking identifiers. To add a function or object to
the module, we assign properties on the special exports object. Alternatively,
we can specify the entire module as a single object, and assign this to module.
exports = myModule .
Modules are loaded with require("my _ module") . This function uses the
paths specified in the require.paths array, which can be modified as we see fit,
just like we did in Listing 14.2. We can also load modules not on the load path by
prefixing the module name with "./" , which causes Node to look for the module
relative to the current module file.
14.2.2 Defining the Module: The First Test
With a basic overview of CommonJS modules, we can write our very first test, as
seen in Listing 14.5. It asserts that the controller object exists, and that it has a
create method.
Listing 14.5 Expecting the controller to exist
var testCase = require("nodeunit").testCase;
var chatRoomController = require("chapp/chat_room_controller");
testCase(exports, "chatRoomController", {
"should be object": function (test) {
Search WWH ::

Custom Search