Skip to content

jurberg/define.js

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

16 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

define.js

A simple way to define modules using the familiar AMD syntax.

Background

The AMD spec provides a clean way to define and use modules. A library like Require.JS works great, but sometimes you don't need the full features. For example, you may be using a framework like Grails that provides it's own way to bundle Javascript. This library was developed to allow using the familiar AMD define syntax, but leave out the loading.

This library differs from other module libaries because it places your module on the global object. This allows to access the module outside of a require call (for example, in an event handler on the html) and it allows you to access other global libraries as modules. For example, you can access jQuery as 'jQuery'.

Usage

  1. Load define.js
  2. Load 3rd party libaries.
  3. Define your modules using the define function.
  4. Manaully load the modules in the correct order.
  5. Enjoy

Unit testing

Sometimes you need to mock out a dependency. The 'redefine' method allows you to reload a module with dependencies mocked out; just pass in an override hash with the module name and the mocked methods. It also takes a callback that allows you to mock out methods on the module itself. Call 'redefine' with only the name to restore the original.

Development

Define.js is built using grunt.js. Run 'npm install', then use grunt commands.

Examples

Define a module

define('domain/person', [], function() {
  var Person = { name: 'John Doe' };
  return {
    createPerson: function() { return Object.create(Person); }
  };
});

Define a module with dependencies

This example uses the person module plus jQuery.

define('view/person', ['domain/person', 'jQuery'], function(Person, $) {
  var person = Person.createPerson();
  return {
    showPerson: function() {
      $('#person-div').html(person.name);
    }
  };
});

Access a module in html

Since modules are defined on the global object, you can access them in html.

<a onclick="view.person.showPerson(); return false;">Show person</a>
<div id="person-div"></div>

Test with a mock

redefine('service/person', { 'domain/person': {
  createPerson: function() {
    return { value: 'my mock data' };
  }
});
require(['service/person'], function(PersonService) {
  // do something with PersonService
});
// call reload with no overrides to reload with no mocks
redefine('service/person');

About

A simple module loader

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published