First you have to get MooTools and make sure the Class and other stuff are
global so you can use  MooTools' stuff everywhere. This is not ideal but
will change in 2.0.

Then you have to make your 'module' and add stuff to the exports object.

MyClass.js

exports.foo = new Class({
    // ...
});


Then you can require it with require()

App.js

var MyClass = require('./MyClass').foo;


This is just how the CommonJS module system works and probably you could
find more information about that searching for that.

Here's another example:
http://wiki.commonjs.org/wiki/Modules/1.1#Sample_Code

If you have a class that you want to use as a server side CommonJS module
(for node.js and other CommonJS implementations) *and* on the client-side in
the browser, you could use something like this:

(function(context){

context.MyClass = new Class({…});

})(typeof exports != 'undefined' ? exports : window);


Finally there's another solution called AMD (
https://github.com/amdjs/amdjs-api/wiki/AMD) which makes sharing modules
between browser and server easier because the CommonJS module specification
is synchronous and not designed for browsers which makes it hard to use in
browsers. AMD solves this and also partially implements the CommonJS modules
inside the factory function (the require, exports and module variables).

Probably MooTools 2.0 will use this and personally I think it's a great way
to structure and modularize your JavaScript. The most popular AMD
implementation is require.js (http://requirejs.org/) which works in the
browser (including a optimizer) and server.

On Fri, Sep 2, 2011 at 11:43 PM, netSQL <[email protected]> wrote:

>  just want to validate that I am using the right approach, 'it
> compiles', but I'm not sure it's optimal.
>
> Basically I copied working code form client side, but made it a server
> side Node file/module 'MyClass.js':
>
> exports = MyClass = new Class({..
>
> (is that right?)
> and then call it the normal way.
>  require('./client/gamina/more/MyClass.js')
>  var sm = new MyClass();
>  sm.foo();
>
> Also in this thread they said MooTools might be slow on server side:
>
> http://groups.google.com/group/nodejs/browse_thread/thread/a244a2c50455d0fc/fe9bf37c461b578f?lnk=gst&q=mootools#fe9bf37c461b578f
> I can't see why.
>
> And last, is there a way I can use the same exact code from client
> side on server side? I don't think so.
>
>
>
>

Reply via email to