Listener Helper Examples

DomenicDenicola edited this page Jan 27, 2012 · 1 revision
Clone this wiki locally

fileCollection.js

var pubit = require("pubit");

var publish = pubit.makeEmitter(exports);

var files = [];

exports.add = function (newFile) {
  files.push(newFile);
  publish("add", newFile);
};

exports.addBulk = function (newFiles) {
  Array.prototype.push.apply(files, newFiles)

  // No need to worry about separate events for single vs. bulk; just use the same add event for both.
  newFiles.forEach(function (newFile) {
    publish("add", newFile);
  });
};

filesReporter.js

var pubit = require("pubit");

function onFilesAdded(newFiles) {
  console.log(newFiles.length + " file(s) added");
}

exports.reportOn = function (fileCollection) {
  fileCollection.on("add", pubit.debouncedListener(onFilesAdded, 100));
};

demo1.js

var fileCollection = require("./fileCollection");
var filesReporter = require("./filesReporter");

filesReporter.reportOn(fileCollection);

filesCollection.add("A");
filesCollection.add("B");
filesCollection.add("C");

// After 100 ms: "3 file(s) were added"
// If we had passed `true` as the third parameter to `debouncedListener`, we would have gotten all three in
//   the next turn of the event loop instead.

demo2.js

var fileCollection = require("./fileCollection");
var filesReporter = require("./filesReporter");

filesReporter.reportOn(fileCollection);

filesCollection.add("1");
setTimeout(function () {
  filesCollection.add("2");
}, 50);
setTimeout(function () {
  filesCollection.add("3");
}, 100);
setTimeout(function () {
  filesCollection.add("4");
}, 150);

// After 250 ms, i.e. 100 ms after the last addition: "4 file(s) added"

// If we had passed `true` as third parameter to `debouncedListener`, we would have gotten:
//  * In the next turn of the event loop: 1 file(s) added (from 1)
//  * After 250 ms: 3 file(s) added (from 2, 3, and 4)

// If we had been throttled instead of debounced, we would have gotten:
//  * After 100 ms: 2 file(s) added (from 1 and 2)
//  * After 200 ms: 2 file(s) added (from 3 and 4)