在javascript中访问对象文字内的函数内的函数?

时间:2017-04-23 23:59:31

标签: javascript cordova

我有一些代码如下 -

var app = {
    initialize: function() {
        document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
        document.addEventListener('backbutton',this.receivedEvent.backbutton(),false);
                                                    ^-- //not working
    },

    onDeviceReady: function() {
        this.receivedEvent('deviceready');
    },

 receivedEvent: function(id) {
    var originalLocation, partnership;

    function fadeOut(element, direction) {
       ....
    };

    function fadeIn(element, direction) {
        .....
    }

    function formFadeIn(direction) {
        fadeIn($("#dataform"), direction);
    };

    function formFadeOut(direction) {
        fadeOut($("#dataform"), direction);
    };

    function backbutton () {
        var current = $("#home").attr("page-current");
        var prev = $("#home").attr("page-prev");
        if (current == "dataform" && prev == "partnertype") {
            formFadeOut("opposite");
            partnertypeFadeIn("opposite");
            setPage("country", "partnertype")
            $("#selectcountry").attr("disabled", false).val("AF")
        } else if (current == "dataform" && prev == "country") {
            formFadeOut("opposite");
            countryFadeIn("opposite");
        } else if (current == "partnertype" && prev == "country") {
            partnertypeFadeOut("opposite");
            countryFadeIn("opposite");
        } else {
            window.location.reload()
        }
    }
}
};

app.initialize();

所以我需要将事件“backbutton”绑定到function backbutton()内的receivedEventfunction backbutton()正在调用receivedEvent中的本地函数,例如formFadeIn()等。

我无法弄清楚绑定的确切语法。

我尝试了什么 -

  1. this.receivedEvent.backbutton //无响应

  2. this.receivedEvent.backbutton() //无响应

  3. this.receivedEvent.bind(this).backbutton //导致页面无限循环

  4. 将backbutton()函数导出为return { backbutton : backbutton } //无响应

  5. 在不丢失上下文的情况下,如何从function backbutton()访问app.initialize()该怎么办?

1 个答案:

答案 0 :(得分:0)

你可以尝试:

var app = {
  initialize: function() {
     document.addEventListener('backbutton',this.myBackButtonFunction, false);
  },

  myBackButtonFunction: function() {
     // Your code
  }
  receivedEvent: function(id) {
     // Can also be invoked from here
    this.myBackButtonFunction(); 
  },

};


app.initialize();