Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...