分解成较小的MVC功能

时间:2016-12-28 14:38:08

标签: javascript jquery ajax function

我有以下功能

 function registerUser(event) {
    event.preventDefault();
    let userData = {
        username: $('#formRegister input[name=username]').val(),
        password: $('#formRegister input[name=passwd]').val()
    };
    $.ajax({
        method: "POST",
        url: kinveyBaseUrl + "user/" + kinveyAppKey + "/",
        headers: kinveyAppAuthHeaders,
        data: JSON.stringify(userData),
        success: registerSuccess,
        error: handleAjaxError
    });
    function registerSuccess(userInfo) {
        saveAuthInSession(userInfo);
        showHideMenuLinks();
        listBooks();
        showInfo('User registration successful.');

    }
}

我尝试按以下方式执行此操作:Direction Controllers包含带有1个函数的RegisterUserController.js文件:

function registerUser(event) {
event.preventDefault();
let userData = {
    username: $('#formRegister input[name=username]').val(),
    password: $('#formRegister input[name=passwd]').val()
};
registerUserAjaxRequest();
function registerSuccess(userInfo) {
    saveAuthInSession(userInfo);
    showHideMenuLinks();
    listBooks();
    showInfo('User registration successful.');
   }
}

在其他Direction Model中包含具有此功能的RegisterUserModel.js文件:

function registerUserAjaxRequest() {
$.ajax({
    method: "POST",
    url: kinveyBaseUrl + "user/" + kinveyAppKey + "/",
    headers: kinveyAppAuthHeaders,
    data: JSON.stringify(userData),
    success: registerSuccess,
    error: handleAjaxError
}});

猜猜是什么,只有当ajax请求在regusterUser函数中时它才起作用。问题是:我如何分解成更小的函数并正确运行?

提前致谢

1 个答案:

答案 0 :(得分:0)

这就是我创造的解决方案。我不确定这是一个好习惯。

那是注册模型:

  function registerUserModel(userData) {
   return $.ajax({
        method: "POST",
        url: kinveyBaseUrl + "user/" + kinveyAppKey + "/",
        headers: kinveyAppAuthHeaders,
        data: JSON.stringify(userData),
        error: handleAjaxError
    });
}

这是注册用户控制器

function registerUser(event) {
    event.preventDefault();
    let userData = {
        username: $('#formRegister input[name=username]').val(),
        password: $('#formRegister input[name=passwd]').val()
    };
    registerUserModel(userData).then(function (userInfo) {
        saveAuthInSession(userInfo);
        showHideMenuLinks();
        showHomeView();
    })
}