Understanding jQuery Deferred.pipe()
I am trying to implement the jQuery Deferred.pipe() method for the following scenario:
- Add a user in DB via $.ajax()
- Get response whether user was added correctly or not.
- If successfully added, get all the user list from server via $.ajax()
- Display the list via jQuery templates
This is something which I tried:
var addUserSuccess = function( data ) {
if ( data.returnCode !== "success" ) {
return $.Deferred().reject('Error saving user');
}
getUsers();
}
var addUser = function()开发者_开发技巧 {
return $.ajax(url, {
type: "POST",
data: { username: 'test' },
contentType: "application/json",
dataType: "json"
});
}
var displayUsers = function( data ) {
$('#myTmpl').tmpl(data.d).appendTo('#myDiv');
}
var getUsers = function () {
return $.ajax(url, {
type: "GET",
data: {},
contentType: "application/json",
dataType: "json"
});
}
$.when(addUser()).pipe(addUserSuccess).then(displayUsers)
But this does not work. I know there is something missing or wrong. Any help?
In addUsersSuccess, you should be returning getUsers. It's a simple typo, you got the main idea perfectly right and are using pipe as it should be and nicely :)
精彩评论