Permalink
Browse files

Fix triggering of queued 'fail' methods on the request. Example:

model.save().fail( function() {
    // Should be triggered when the request fails
}
  • Loading branch information...
1 parent a2d1da7 commit a04f78f29a4e04e93673ed63fe905ebd08425111 @PaulUithol PaulUithol committed Sep 14, 2011
Showing with 37 additions and 3 deletions.
  1. +7 −2 backbone_tastypie/static/js/backbone-tastypie.js
  2. +30 −1 test/tests.js
@@ -18,8 +18,8 @@
if ( method === 'create' ) {
var dfd = new $.Deferred();
- var success = options.success;
- dfd.done( success );
+ // Set up 'success' handling
+ dfd.done( options.success );
options.success = function( resp, status, xhr ) {
// If create is successful but doesn't return a response, fire an extra GET.
// Otherwise, resolve the deferred (which triggers the original 'success' callbacks).
@@ -36,6 +36,11 @@
}
};
+ // Set up 'error' handling
+ dfd.fail( options.error );
+ options.error = dfd.reject;
+
+ // Make the request, make it accessibly by assigning it to the 'request' property on the deferred
dfd.request = Backbone.oldSync( method, model, options );
return dfd;
}
View
@@ -94,7 +94,7 @@ $(document).ready(function() {
});
test( "Success callbacks are triggered, receive proper parameters", function() {
- expect( 4 );
+ expect( 6 );
var emptyResponse = '';
var response = { id: 1, 'resource_uri': '/animal/1/' };
@@ -108,18 +108,47 @@ $(document).ready(function() {
// Request with a response
var animal = new Animal( { species: 'Turtle' } );
var dfd = animal.save( null, { success: successCallback } );
+ // Add another 'success' callback
+ dfd.done( function() {
+ ok( true, "Done triggered" );
+ });
// Do the server's job
dfd.request.success( response, 'created', xhr );
// Request without a response right away, response in second request
animal = new Animal( { species: 'Lion' } );
dfd = animal.save( null, { success: successCallback } );
+ // Add another 'success' callback
+ dfd.done( function() {
+ ok( true, "Done triggered" );
+ });
// Do the server's job
var secondRequest = dfd.request.success( emptyResponse, 'created', xhr );
secondRequest.success( response, 'get', { status: 200 } );
});
+
+ test( "Error callbacks are triggered, receive proper parameters", function() {
+ expect( 2 );
+
+ var xhr = { status: 404 };
+
+ var errorCallback = function( model, resp, options ) {
+ equals( resp.status, 404 );
+ };
+
+ // Request with a response
+ var animal = new Animal( { species: 'Turtle' } );
+ var dfd = animal.save( null, { error: errorCallback } );
+ // Add another 'error' callback
+ dfd.fail( function() {
+ ok( true, "Fail triggered" );
+ });
+
+ // Do the server's job
+ dfd.request.error( xhr, 'error', 'Not found' );
+ });
module("Model url building", { setup: initObjects } );

0 comments on commit a04f78f

Please sign in to comment.