Understanding jQuery Deferred.pipe()

送分小仙女□ 提交于 2019-11-27 01:49:46

问题


I am trying to implement the jQuery Deferred.pipe() method for the following scenario:

  1. Add a user in DB via $.ajax()
  2. Get response whether user was added correctly or not.
  3. If successfully added, get all the user list from server via $.ajax()
  4. 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?


回答1:


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 :)



来源:https://stackoverflow.com/questions/5921283/understanding-jquery-deferred-pipe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!