wootscootinboogie
wootscootinboogie

Reputation: 8695

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?

Upvotes: 0

Views: 45

Answers (2)

Felix Kling
Felix Kling

Reputation: 816482

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.

Upvotes: 1

user2672373
user2672373

Reputation:

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));

Upvotes: 0

Related Questions