Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Q library in browser

I need to use Q library (http://documentup.com/kriskowal/q/) in the browser. I would like to use RequireJS to load this library, but I don't have any idea how to do this. I know how to load my own module, but I can't do it with Q. It has some function:

(function (definition) { 
  //some another code here***
  // RequireJS
} else if (typeof define === "function" && define.amd) {
  define(definition);

How can I load Q and then use it in another module?

like image 333
user2365163 Avatar asked Aug 20 '13 05:08

user2365163


1 Answers

The proper AMD way of doing this would be (borrowed example code from @Eamonn O'Brien-Strain):

requirejs.config({
  paths: {
    Q: 'lib/q'
  }
});

function square(x) {
  return x * x;
}

function plus1(x) {
  return x + 1;
}

require(["Q"], function (q) {
  q.fcall(function () {
    return 4;
  })
    .then(plus1)
    .then(square)
    .then(function (z) {
      alert("square of (value+1) = " + z);
    });
});

This way Q doesn't leak to the global scope and it's easy to find all modules depending on this library.

like image 99
kryger Avatar answered Sep 22 '22 05:09

kryger