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

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

javascript - jQuery - trigger not produce the expected result

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

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

1 Answer

0 votes
by (71.8m points)

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));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...