簡體   English   中英

使用parse.com javascript SDK丟失上下文

[英]Losing context with parse.com javascript SDK

因此,我要做的目標是在對象文字中存儲對象數組以供以后參考。 我在一個令我困惑的地方失去了上下文(如果這是在這里使用的正確術語)。 這是代碼:

HuntObject = {

        // Data.hunts gives collection
        Data: {},

        fetchCollec: function(){
            var self = this;

            var huntObj = new Parse.Query(huntObject);
            huntObj.find({
                success: function(results){
                    var hunts = [];

                    for(i in results){
                        hunts.push(i);
                    }
                    console.log(self);
                            //Here self references HuntObject
                    self.Data = hunts;



                },

                error: function(e){
                    console.log(e.message);
                }
            });

            console.log(self);// Here self references HuntObject 
                            console.log(self.Data); // empty

因此,在我的console.log語句中,都引用了我想要的正確上下文,並且在上一次對self的日志調用中,我什至可以在控制台中看到Data對象現在具有對象數組。 但是,比起我嘗試引用該數組時,我得到一個空的對象。 我嘗試以不同的方式分配數組,例如self.Data.array = hunts。 我還嘗試將數據設置為這種方法。

Data: (function(){
        return {
            array: []
        }
     }());

我認為也許我對不同情況下上下文變化的了解還很薄弱,所以解決我的最初目標會很好,但更重要的是,我想更好地理解上下文以及為什么我的實現在這種情況下會失敗?

這不是范圍或上下文問題,您可以使用self變量來處理。

我的猜測是Parse.Query異步的 因此,您必須成功函數中執行console.log 在調用Parse.Query之后立即在代碼中執行此操作(在查詢完成之前)調用它為時過早。

所以:

huntObj.find({
    success: function (results) {
        var hunts = [];

        for (i in results) {
            hunts.push(i);
        }
        console.log(self);
        //Here self references HuntObject
        self.Data = hunts;

        // *********** Move these here
        console.log(self); // Here self references HuntObje
        console.log(self.Data); // Not empty anymore
    },

    error: function (e) {
        console.log(e.message);
    }
});

// Any code here runs after you've *started* the query, but
// before it *completes*

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM