简体   繁体   中英

Using JavaScript modules in external files

I have a skeleton of a module which adds a record to a database with a button click.

var Person = (function () {
    var ajaxOpts = {
        type: "POST",
        url: "",
        contentType: "application/json",
        dataType: "json",
        success: function () { },
        error: function () { },
        data: {}
    }
    function insert(data) {
        ajaxOpts.url = "../Service.asmx/InsertPerson";
        ajaxOpts.data = JSON.stringify(data);
        ajaxOpts.error = function (xhr) {
            console.log(xhr.status);

        };
        ajaxOpts.success = function (data) {
            console.log('record successfully added');
            console.log(data.d);

        }
        $.ajax(ajaxOpts);
    };
    return {
        insert: insert
    }
} ());

and I call it from my webpage like:

$(document).ready(function () {
            $('#btnSubmit').click(function () {
                var data = {
                    personId: $('#personId').val(),
                    firstName: $('#firstName').val(),
                    lastName: $('#lastName').val()
                };
                Person.insert(data);
            });
        });

How can I modify this code to make sure that $ is the jQuery object and not another library?

For plugins you usually wrap the code in an IIFE and map jQuery to $ . You could do the same for your module (you even already have an IIFE):

var Person = (function($) {
    // ...
}(jQuery));

For document.ready callbacks, a reference to jQuery is passed to the callback:

jQuery(document).ready(function($) {
    // ...
});

Just make sure that you are using jQuery outside of the functions.

How about replacing code in your main page like this:

(function($) {
    $('#btnSubmit').click(function () {
        var data = {
            personId: $('#personId').val(),
            firstName: $('#firstName').val(),
            lastName: $('#lastName').val()
        };
        Person.insert(data);
    });
}(jQuery));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM