[英]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? 我如何修改此代码以确保$
是jQuery对象而不是另一个库?
For plugins you usually wrap the code in an IIFE and map jQuery
to $
. 对于插件,通常将代码包装在IIFE中,然后将jQuery
映射到$
。 You could do the same for your module (you even already have an IIFE): 您可以对模块执行相同的操作(甚至已经拥有IIFE):
var Person = (function($) {
// ...
}(jQuery));
For document.ready
callbacks, a reference to jQuery is passed to the callback: 对于document.ready
回调,将对jQuery的引用传递给该回调:
jQuery(document).ready(function($) {
// ...
});
Just make sure that you are using jQuery
outside of the functions. 只要确保您在函数之外使用jQuery
。
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.