Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

v2: Backbone.Promise #3651

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 30 additions & 5 deletions backbone.js
Original file line number Diff line number Diff line change
Expand Up @@ -601,9 +601,9 @@
// `set(attr).save(null, opts)` with validation. Otherwise, check if
// the model will be valid when the attributes, if any, are set.
if (attrs && !wait) {
if (!this.set(attrs, options)) return false;
if (!this.set(attrs, options)) return Backbone.Promise.reject(this.validationError);
} else {
if (!this._validate(attrs, options)) return false;
if (!this._validate(attrs, options)) return Backbone.Promise.reject(this.validationError);
}

// After a successful server-side save, the client is (optionally)
Expand Down Expand Up @@ -639,7 +639,7 @@
// Optimistically removes the model from its collection, if it has one.
// If `wait: true` is passed, waits for the server to respond before removal.
destroy: function(options) {
options = options ? _.clone(options) : {};
options = _.extend({}, options);
var model = this;
var success = options.success;
var wait = options.wait;
Expand All @@ -655,9 +655,9 @@
if (!model.isNew()) model.trigger('sync', model, resp, options);
};

var xhr = false;
var xhr;
if (this.isNew()) {
_.defer(options.success);
xhr = Backbone.Promise.resolve().then(options.success);
} else {
wrapError(this, options);
xhr = this.sync('delete', this, options);
Expand Down Expand Up @@ -1408,6 +1408,31 @@
return Backbone.$.ajax.apply(Backbone.$, arguments);
};

// A psuedo Promise implementation used to ensure asynchronous methods
// return thenables.
// Override this if you'd like to use a different ES6 library.
Backbone.Promise = function() {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd say a promise implementation should be included by default (I would suggest npo)

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I disagree (feel free to convince me). This seems very similar to polyfilling JSON, which we do not provide a default implementation of.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The difference is BB doesn't use JSON directly. Though I'd be fine with just assuming Promise is defined globally

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm also a little wishy-washy about depending on jQuery's Deferreds. They're badly non-standard, and we're now demanding a dependency on jQuery (or some other promise library) for Models and Collections to work.

We could go our "jQuery require" route, attempting to require some library 'promise', then feed that into the factory function. Or just require overwriting BB.Promise on node if you want to use async methods. Hmmm.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could go our "jQuery require" route, attempting to require some library 'promise', then feed that into the factory function. Or just require overwriting BB.Promise on node if you want to use async methods. Hmmm.

As of ES6, we can just expect Promise it to be a builtin global (and it is already in many environments) so it'd be exactly as Brad describes, the same as polyfilling JSON. The only requirement here would be that BB wouldn't depend on any specific non-standard library specific methods/helpers.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about a if (typeof Promise != "undefined") Backbone.Promise = Promise
line right after our ponyfill using deferreds? You should probably be
pollyfilling Promise anyways if you need it.

On Sun, May 31, 2015, 21:23 Tim Griesser [email protected] wrote:

In backbone.js
#3651 (comment):

@@ -1408,6 +1408,31 @@
return Backbone.$.ajax.apply(Backbone.$, arguments);
};

  • // A psuedo Promise implementation used to ensure asynchronous methods
  • // return thenables.
  • // Override this if you'd like to use a different ES6 library.
  • Backbone.Promise = function() {

We could go our "jQuery require" route, attempting to require some
library 'promise', then feed that into the factory function. Or just
require overwriting BB.Promise on node if you want to use async methods.
Hmmm.

As of ES6, we can just expect Promise it to be a builtin global (and it
is already in many environments http://caniuse.com/#search=promise) so
it'd be exactly as Brad describes, the same as polyfilling JSON. The only
requirement here would be that BB wouldn't depend on any specific
non-standard library specific methods/helpers.


Reply to this email directly or view it on GitHub
https://github.com/jashkenas/backbone/pull/3651/files#r31396998.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could do a fallback system:

if (root.Promise) {
  BB.Promise = root.Promise;
} else if (Backbone.$) {
  BB.Promise = jQueryDeferredWrapper;
} else {
  BB.Promise = GiveHelpfulErrorMessagesAKAYouAintGotNoPromises; // :wink:
}

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

-1 for jquery fallback, the implementation differs to greatly from the
promise spec
On Jun 1, 2015 11:06 AM, "Justin Ridgewell" [email protected]
wrote:

In backbone.js
#3651 (comment):

@@ -1408,6 +1408,31 @@
return Backbone.$.ajax.apply(Backbone.$, arguments);
};

  • // A psuedo Promise implementation used to ensure asynchronous methods
  • // return thenables.
  • // Override this if you'd like to use a different ES6 library.
  • Backbone.Promise = function() {

We could do a fallback system:

if (root.Promise) {
BB.Promise = root.Promise;
} else if (Backbone.$) {
BB.Promise = jQueryDeferredWrapper;
} else {
BB.Promise = GiveHelpfulErrorMessageAKAYouAintGotNoPromises; // :wink:
}


Reply to this email directly or view it on GitHub
https://github.com/jashkenas/backbone/pull/3651/files#r31434073.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@megawac but does it fail for our use case here? Backbone and Underscore tend to opt for the ponyfill approach over pollyfills, encapsulating the desired behavior in functions instead of shimming support globally.

If we force a Promise library (or a Promise global), it'll be confusing to developers why this fails in older browsers but works in newer ones. On the other hand if we set the precedent here that we're ok with making users pollyfill older behaviors, we can start to follow the lead of React in requiring developers to pollyfill native methods (map, forEach, etc).

throw new Error('Backbone does not provide a spec compliant Promise by default.');
};

_.extend(Backbone.Promise, {
// A wrapper around jQuery's normal resolve to force it to adopt a
// thenable's state, and execute then callbacks asynchronously.
resolve: function(value) {
var deferred = Backbone.$.Deferred();
_.defer(deferred.resolve);
return deferred.promise().then(_.constant(value));
},

// A wrapper around jQuery's normal reject to force it to execute
// then callbacks asynchronously.
reject: function(reason) {
var deferred = Backbone.$.Deferred();
_.defer(deferred.reject, reason);
return deferred.promise();
}
});

// Backbone.Router
// ---------------

Expand Down
1 change: 1 addition & 0 deletions test/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,6 @@
<script src="router.js"></script>
<script src="view.js"></script>
<script src="sync.js"></script>
<script src="promise.js"></script>
</body>
</html>
23 changes: 18 additions & 5 deletions test/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -662,13 +662,19 @@
this.ajaxSettings.success();
});

test("destroy", 3, function() {
asyncTest("destroy", 3, function() {
doc.destroy();
equal(this.syncArgs.method, 'delete');
ok(_.isEqual(this.syncArgs.model, doc));

var newModel = new Backbone.Model;
equal(newModel.destroy(), false);
var promise = newModel.destroy();
var async = false;
promise.then(function() {
ok(async, 'then chains asynchronously');
start();
});
async = true;
});

test("destroy will pass extra options to success callback", 1, function () {
Expand Down Expand Up @@ -1156,11 +1162,18 @@
}});
});

test("#1433 - Save: An invalid model cannot be persisted.", 1, function() {
asyncTest("#1433 - Save: An invalid model cannot be persisted.", 2, function() {
var model = new Backbone.Model;
model.validate = function(){ return 'invalid'; };
model.validate = function(){ return { error: 'invalid' }; };
model.sync = function(){ ok(false); };
strictEqual(model.save(), false);
var promise = model.save();
var async = false;
promise.then(null, function(reason) {
strictEqual(reason, model.validationError, 'passes error to onRejected');
ok(async, 'then chains asynchronously');
start();
})
async = true;
});

test("#1377 - Save without attrs triggers 'error'.", 1, function() {
Expand Down
56 changes: 56 additions & 0 deletions test/promise.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
(function() {

module("Backbone.Promise");

test("throws an error if invoked", 1, function() {
try {
Backbone.Promise();
} catch (e) {
ok(e);
}
});

asyncTest(".resolve to passed in value", 1, function() {
var value = {};
Backbone.Promise.resolve({}).then(function(val) {
strictEqual(val, value);
start();
});
});

asyncTest(".resolve adopts promise state", 1, function() {
var value = {};
var promise = Backbone.Promise.resolve(val);
Backbone.Promise.resolve(promise).then(function(val) {
strictEqual(val, value);
start();
});
});

asyncTest(".resolve executes then callback asynchronously", 1, function() {
var async = false;
Backbone.Promise.resolve().then(function() {
ok(async);
start();
});
async = true;
});

asyncTest(".reject to passed in value", 1, function() {
var value = {};
Backbone.Promise.reject({}).then(null, function(val) {
strictEqual(val, value);
start();
});
});

asyncTest(".reject executes then callback asynchronously", 1, function() {
var async = false;
Backbone.Promise.reject().then(null, function() {
ok(async);
start();
});
async = true;
});

});