我早些时候从我正在查看的 PhoneGap/cordova 文件中发现了这个:
var app = {
initialize: function() {
this.bind();
},
bind: function() {
document.addEventListener('deviceready', this.deviceready, false);
},
deviceready: function() {
// This is an event handler function, which means the scope is the event.
// So, we must explicitly called `app.report()` instead of `this.report()`.
app.report('deviceready');
app.handleLogin();
},
}
我只是想知道这样做与在 body 负荷下执行独立功能相比有什么好处?此外,如果我要在 jquery mobile 中的“pagebeforeload”上运行一个函数,我将如何将其集成到上述模式中?如:
$( '#mainMenu' ).live( 'pagebeforeshow', function(event){
alert('pagebeforeshow');
});
最佳答案
简而言之,命名空间。
在 JavaScript 中,一切都是全局的,除非你明确地让它不是全局的。这意味着事物的名称可能会发生冲突,或者您可以覆盖您不想覆盖的事物。这在较大的程序中是个大问题。
您显示的模式将应用程序的所有功能命名空间放入单个 app
“对象”中。因此,任何在全局范围内覆盖 bind
的内容都不会影响 app.bind
的值。命名空间保护它。
一个好的经验法则是尽可能少地污染全局命名空间。在本例中,您将 app
设为全局,仅此而已。你所有的代码都依赖于那个全局值。干净整洁。
关于如何整合你的例子。我可能会这样做:
var app = {
initialize: function() {
app.bindEventHandlers();
// other setup code called here...
},
bindEventHandlers: function() {
$( '#mainMenu' ).live( 'pagebeforeshow', app.pageBeforeShow );
// other event handlers bound here...
},
pageBeforeShow: function() {
alert('pagebeforeshow');
},
// other event handler functions declared here...
// or whatever other functions or data your app needs here...
}
// start your app when the document is ready
$(document).ready(function() {
app.initialize();
});
关于javascript - 编写将所有内容都放在变量中的 Javascript 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14714963/