将jQuery代码拆分为可重用的模块

时间:2018-11-18 13:01:26

标签: javascript jquery module refactoring node-modules

我正处于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一起使用。 / p>

简而言之,我相信有更好的方式编写这段代码。我想这个特定的例子太复杂了,可以作为提交事件中关闭的jquery代码保留下来。但是,我坚持要使其模块化,因为我想在此示例中学习并自己重构其余代码。

另外,我需要能够不使用init()方法而访问“ beforeSend”和“ after”之类的方法,因为我正在其他模块中使用无格式的ajax调用时引用此方法-我仍然想显示在ajax操作期间将叠加层加载到给定容器上。

0 个答案:

没有答案
相关问题