开发者

How to I set a prototype object when a JSON object returns (and that object is out of scope)?

开发者 https://www.devze.com 2023-03-18 10:06 出处:网络
I have the following object: //the constructor function function NewsScroller() { } //now put some config objects using the JSON structure

I have the following object:

 //the constructor function
    function NewsScroller() {

    }


    //now put some config objects using the JSON structure
    NewsScroller.prototype.config = {
        serviceUrl : '/NewsProvider.svc/rest/GetNews/',
        pageIndex : 0,
        pageNumbers: 0
    }

//allows the sending of a page
NewsScroller.prototype.getNews = function (pageIndex) {

    //get all the newsItems
    var urlToGetJson = this.config.serviceUrl + pageIndex;


    $.getJSON(urlToGetJson, function (data) {


    alert(this.config.pageNumbers);


        $.each(data.NewsItems, function (i, item) {

            var item1DateSelector = '.scroller-pane #division-' + i + ' .date';
            $(item1DateSelector).html(formattedDate);

        });

    });


}

Whi开发者_高级运维ch throws the error:

this.config is undefined [Break On This Error] alert(this.config.pageNumbers);

I can see from looking at the code I cannot access the prototype so I have 2 questions:

1) Why cant I access why is it out of scope? Surely a function in a function has access to the memebers contained within that function? 2) If I cant access it how do I set the object 'pageNumbers' in the 'config' object notation?


It's out of scope because this loses context, since it's jQuery's ajax callback that is executing the function. Indeed other variables retain their lexical scope, so you can solve this with the self=this pattern, or try binding the function:

NewsScroller.prototype.getNews = function (pageIndex) {

    //get all the newsItems
    var urlToGetJson = this.config.serviceUrl + pageIndex;
    function ajaxCallback(data) {
        alert(this.config.pageNumbers);
        $.each(data.NewsItems, function (i, item) {
            var item1DateSelector = '.scroller-pane #division-' + i + ' .date';
            $(item1DateSelector).html(formattedDate);
        });
    }

    $.getJSON(urlToGetJson, $.proxy(ajaxCallback, this));

}

Using the self=this pattern:

NewsScroller.prototype.getNews = function (pageIndex) {

    //get all the newsItems
    var urlToGetJson = this.config.serviceUrl + pageIndex,
        self = this;

    $.getJSON(urlToGetJson, function(data) {
        alert(self.config.pageNumbers); // instead of this, we reference self
        $.each(data.NewsItems, function (i, item) {
            var item1DateSelector = '.scroller-pane #division-' + i + ' .date';
            $(item1DateSelector).html(formattedDate);
        });
    });

}
0

精彩评论

暂无评论...
验证码 换一张
取 消