Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In my app, while page load i initiate my init function for 3 things,

  1. trigger and sending a page no. (i would like to pass page default as 1)

  2. when trigger done, i want to hear that so i am listening

  3. again, a user can insert / edit the page number (text box) so i am adding a listener to function.

but when function start i am consoling a object but i am getting result as undifined.

what is wrong here:

var docLoader = function (params) {

    window.container = window.container || $("#tenderContent");

    return {
        init : function () {
            this.cachePages = {};
            $(document).on("newMessage", this.onPageChange);
            $.event.trigger({
                type: "newMessage"
            });
        },

        onPageChange : function (e) {
            console.log(this.cachePages) //undefined why?
        }
    }
}

html page :

<script>
    docLoader().init();
</script>

I am new to de-coupled approach any one help me with details please?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
195 views
Welcome To Ask or Share your Answers For Others

1 Answer

It's because you lose the this context. jQuery passes the DOM element as the context, not whatever the original context was.

You need to bind the context of the function to your existing this:

$(document).on("newMessage", this.onPageChange.bind(this));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...