首页 > 解决方案 > 将 jQuery 代码拆分为可重用的模块

问题描述

我正在进行 php 应用程序开发,并添加了一些 js。由于我的JS知识不是特别好,所以我依赖jQuery。但是,我喜欢使用可重用的代码而不是意大利面条。所以,有一种情况。

我在应用程序中有两种形式 - 经典的和 ajax 的。现在我想将我的 ajax 表单处理程序移动到单独的文件、模块并在主 js 文件中启动它。让我们看看我的正确代码:

main.js

import forms from './plugins/ajaxForms';

forms.init($('form.ajax'));

ajaxForms.js

function init(form) {
    const obj = this;
    form.on('submit', function (e) {
        e.preventDefault();
        const form = $(this);
        const url = form.attr('action');
        const data = form.serialize();
        const method = form.find('input[name="method"]').val() ? form.find('input[name="method"]').val() : form.attr('method');

        const call = $.ajax({
            type: method,
            url: url,
            data: data,
            dataType: "json",
            beforeSend: function() {
            obj.beforeSend(form);
            }
        });

        call.done(function (response) {
            Toastr["success"](response.message);
        });

        call.fail(function (response) {
            Toastr["error"](response.responseJSON.message);
            obj.renderErrors(form);
        });

        call.always(function () {
            obj.after(form);
        });
    });
}

function beforeSend(container) {
    if(container === null) {
    return;
    }
    container.find('.form-loading-overlay').show();
}

function after(container) {
    if(container === null) {
    return;
    }
    container.find('.form-loading-overlay').hide();
}

function renderErrors(errors, form) {
    $.each(errors, function (i, e) {
    if (Array.isArray(e)) {
        let output = '';
        $.each(e, function (i,e) {
            output += e + '<br />';
        });

        form.find('input[name="' + i + '"]')
            .after('<span class="error">' + output + '</span>')
            .addClass('has-error');

    } else {
        form.find('input[name="' + i + '"]')
            .after('<span class="error">' + e + '</span>')
            .addClass('has-error');
    }
    });

}


export default {
    init: init,
    beforeSend: beforeSend,
    after: after,
    renderErrors: renderErrors
};

注意:renderErrors 函数当前不工作,因为它与表单变量有问题。现在没关系。

预期的解决方案:

我不喜欢使用此模块中的其他函数的方式(例如 after(container) - 我需要将“this”传递给 const obj 以使其与 const 调用中的 beforeSend 一起使用。

简而言之,我相信有更好的方法来编写这段代码。我想这个特定的例子过于复杂,可能只是作为一个 jquery 代码在提交事件中关闭。但是,我坚持将其模块化,因为我想在这个示例中学习并自己重构我的其余代码。

此外,我需要能够在不使用 init() 方法的情况下访问诸如“beforeSend”和“after”之类的方法,因为我在使用没有表单的 ajax 调用时在其他模块中引用此方法 - 我仍然想显示加载覆盖在 ajax 操作期间给定容器。

标签: javascriptjquerymodulerefactoringnode-modules

解决方案


推荐阅读