我正在尝试理解 JavaScript 模块模式。我已经看过它应该是什么样子的示例,但我不明白如何使用它。
例如,这里发生了一些事情:
$('input#share').on("click", function() {
$('.loading').html('<img class="remove_loading" src="/graphics/loading.gif" />');
var message = $(".wallmessage").val();
if (message == ""){
$("#messageempty").jmNotify();
$('.remove_loading').remove();
} else {
addMessage(message);
}
return false;
});
function addMessage(message)
{
$.ajax({
url: '/test',
type: 'POST',
dataType: "json",
data: {'message' : message},
success: function(data) {
...
},
error: function() {
...
}
});
}
我如何使用上面的示例:
var myTest = function() {
var selectId;
function addMessage () {
// ...
}
return { // public interface
publicMethod1: function () {
// all private members are accesible here
}
};
};
var start = myTest();
我在哪里添加点击事件,声明我的变量,添加addMessage
函数与ajax调用。并致电addMessage
功能?我必须把所有东西都包起来吗$(document).ready(function()
?
有人能为我解释一下吗?
Thanks
这是一个相当固执己见的主题,但我会这样做(不完全了解你的完整应用程序及其用途),有点像这样:
var myApp = (function() {
var someElement = $("#foo"); //some element I know I'll use lots
var addMessage = function(message) {
$.ajax({
url: '/test',
type: 'POST',
dataType: "json",
data: {'message' : message},
success: function(data) {
...
},
error: function() {
...
}
});
};
var inputClick = function(event) {
event.preventDefault();
//depending on if you'll reuse these selectors throughout the app I might have these as variables
$('.loading').html('<img class="remove_loading" src="/graphics/loading.gif" />');
var message = $(".wallmessage").val();
if (message == ""){
$("#messageempty").jmNotify();
$('.remove_loading').remove();
} else {
addMessage(message);
}
};
var bindFunctions = function() {
$("input#share").on("click", inputClick)
};
var init = function() {
bindFunctions();
};
return {
// EDIT: 27/12/16 - need to return init for 'usage' example to work
init: init,
addMessage: addMessage
//anything else you want available
//through myApp.function()
//or expose variables here too
};
})();
//usage
myApp.init();
您的模式的原始代码是错误的,该功能必须有()
最后,使其成为一个函数立即调用,然后执行,通过return statement
.
您可能希望与我所做的略有不同,这只是一个基本想法,但我希望它可以帮助您入门。
不久前有人提出了与此模式相关的问题,并且我回答了 https://stackoverflow.com/questions/6562679/what-is-the-use-of-return-statement-inside-a-function/6562710#6562710解释我们为什么使用(function() {})();
以及如何return
声明在这种情况下有效,如果您对此感到有点困惑,那么也可能值得一读。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)