在不破坏未定义函数的情况下,对多个视图使用单个js文件

use single js file for multiple views without breaking on undefined function

本文关键字:视图 文件 js 单个 未定义 函数 情况下      更新时间:2023-09-26

我有一个用于编辑后端的js文件。问题是,对于视图A,我只需要少数方法,对于视图B,我需要另一个集合,但我从不需要两个页面上的任何方法。

我决定将两个视图的所有jquery都放在一个文件中,但当选择器不可用并且jquery的其余部分不再解析时,它就会中断。这会导致页面不可用。

有没有一种方法可以使用一个jquery文件,包含所有视图的所有方法,即使存在未定义的函数异常?

$("#mal_search").select2({
    ajax: {
        url: "/api/mal/search",
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
                q: params.term, // search term
                page: params.page
            };
        },
        processResults: function (data, page) {
            // In case a single result is returned we put the
            // data object into an array otherwise select2 will
            // not be able to read the object
            if (!$.isArray(data)) {
                data = [data];
            }
            return {
                results: data
            };
        },
        cache: true
    },
    escapeMarkup: function (markup) {
        return markup;
    }, // let our custom formatter work
    minimumInputLength: 1,
    templateResult: formatRepo, // omitted for brevity, see the source of this page
    templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
///////////////////////////////////
// The following doesn't work if the above method throws a is not a function exception
$('#filename-url-container').on('click', '.btn-add', function (e) {
    var formGroup = $('#filename-url-container > :first-child').first().clone(true);
    formGroup.find('input').val('');   // erase values
    $('#filename-url-container').append(formGroup);
    formGroup.closest('button.btn-add')
        .removeClass('btn-add').addClass('btn-remove')
        .removeClass('btn-success').addClass('btn-danger')
        .html('<span class="glyphicon glyphicon-minus"></span>');
}).on('click', '.btn-remove', function (e) {
    $(this).closest('.form-group').remove();
});

提升是指在定义函数/变量之前使用它,如链接中所述。提升本身不是问题,但会使代码泄漏全局变量,其他开发人员很难阅读。所以你不应该这么做,"但你可以"

关于分手。正如您所知,哪些函数将在page1上使用,哪些函数在page2上使用,请将它们放在文件page1.js和page2.js中,并将它们加载到页面上。你也可以把它们都放在一个文件中,并有一个startPage1函数和一个startPage2函数,可以按照你想要的方式启动页面。遗憾的是,如果没有更多的代码,我无法帮助你