编写包含变量中所有内容的Javascript代码

时间:2013-02-05 19:05:31

标签: javascript jquery cordova

我之前从我正在浏览的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();
    },
  }

我只是想知道这样做的好处是什么,而不是在身体负载上执行的独立功能?另外如果我要在jquery mobile中的“pagebeforeload”上运行一个函数,我该如何将它集成到上面的模式中呢?如:

    $( '#mainMenu' ).live( 'pagebeforeshow', function(event){
    alert('pagebeforeshow');
});

2 个答案:

答案 0 :(得分:4)

简而言之,命名空间。

在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();
  });

答案 1 :(得分:1)

如果您使用OOP语言,那么您就知道了类的定义。 JS不支持class-keyword,因此要使用方法创建对象,应使用以下代码。然后你可以调用app.initialize()。此外,它还可以为您提供应用程序架构的高级功能。

将代码集成到您应该原型化的现有功能中。

app.prototype = { nameOfFunctionHere: function() { alert('pagebeforeshow'); } }

然后只需致电

app.nameOfFunctionHere();

执行你的功能