Remarks about module import

Kris Kowal kris.kowal at
Sat Aug 23 19:16:39 PDT 2008


> Can you provide concrete examples (something a few lines longer than a
> hello world module) which shows both the module and importer code?


    this module provides a `sink` function which allows the
    user to cause a DOM element to forward its events to
    one and only one, detachable Widget object that implements

/* these are modules by the same author, in the same directory */
from "./urllib.js" import urlJoin;
from "./base.js" import Set;
/* this is a cross-browser compatibility layer */
from "./browser.js" import normalizeEventName, browserEventName;
/* presumably "browser" is a module provided by the browser in some
 * cross-browser compatible way. */
from "chrome://js/browser.js" import observe;

/* using let or var makes a variable private to the module */
let widgetNs = urlJoin(__FILE__, '#widget'); // or
let widgetNs = urlJoin(moduleUrl, '#widget');
let sinksAttribute = urlJoin(__file__, '#sinks');
/* the name __FILE__, moduleUrl, __file__, or __DIR__
 * isn't as important as the behavior.  It would not
 * be onerous to provide both module file and dir variables,
 * but dir can be inferred from file and is best
 * dealt with via urlJoin which handles both cases unless
 * the provider of __DIR__ is unscrupulous about the
 * final forward-slash. */

/* assigning to "this" makes it an export */
this.sink = function (element, widget, eventName) {
    if (element[widgetNs] && element[widgetNs] != widget) {
    element[widgetNs] = widget;
    let sinks = element.getAttribute(sinksAttribute);
    element[sinksNs] = sinks;

    let normalizedEventName = normalizeEventName(eventName);
    let browserEventName = browserEventName(eventName);

    if (!sinks.has(normalizedEventName)) {
        observe(element, browserEventName, function () {
            let widget =[widgetNs];
            widget.signal(normalizedEventName, this);

    /* break reference cycles */
    widget = undefined;
    element = undefined;


from "./sink.js" import sink; // or
let sink = require("./sink.js").sink;
from "" import jQuery as $
from "./my-widget.js" import MyWidget
sink($('#widget'), MyWidget());

Kris Kowal

More information about the Es-discuss mailing list