Skip to content

Commit

Permalink
Add Q.noConflict function
Browse files Browse the repository at this point in the history
Fixes kriskowal#677

This commit adds a function that is basically a noop. It simply alerts the user that they should not be using `Q.noConflict` when they are not using Q as a global.

If Q finds itself sourced as a `<script>` it will store the original value of `Q` and overwites `Q.noConflict` function with an actual implementation. `Q.noConflict` returns a refernce to `Q`.
  • Loading branch information
kahnvex committed Apr 27, 2015
1 parent ed721ca commit 80c7666
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
17 changes: 16 additions & 1 deletion q.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,18 @@

// <script>
} else {
Q = definition();
// Get the `window` object, save the previous Q global
// and initialize Q as a global.
var root = this;
var previousQ = root.Q;
root.Q = definition();

// Add a noConflict object so Q can be removed from the
// global namespace.
root.Q.noConflict = function() {
root.Q = previousQ;
return this;
};
}

})(function () {
Expand Down Expand Up @@ -1900,6 +1911,10 @@ Promise.prototype.nodeify = function (nodeback) {
}
};

Q.noConflict = function() {
console.log('Q.noConflict only works when Q is used as a global');
};

// All code before this point will be filtered from stack traces.
var qEndingLine = captureLine();

Expand Down
21 changes: 21 additions & 0 deletions spec/q-spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -2169,6 +2169,27 @@ describe("node support", function () {

});

describe("browser support", function () {
var _Q;

beforeEach(function() {
_Q = Q;
});

afterEach(function() {
Q = _Q;
});

it("sets the global Q object to its original value", function() {
Q.noConflict();

// In this context the original value of Q is undefined.
if(typeof window === 'object') {
expect(Q).toEqual(undefined);
}
});
});

describe("isPromise", function () {
it("returns true if passed a promise", function () {
expect(Q.isPromise(Q(10))).toBe(true);
Expand Down

0 comments on commit 80c7666

Please sign in to comment.