簡體   English   中英

Backbone model.fetch()回調(調用setTimeout)內的范圍問題

[英]Scope issue within Backbone model.fetch() callback (calling setTimeout)

我有一個主視圖( Services )和一個子視圖( Service )的集合。 每個子視圖需要每5秒刷新一次。 為此,我有以下[摘錄]:

Service: Backbone.View.extend({
    ...

    initialize: function () {
        this.model.bind('change', this.render, this);
        _.bindAll(this, 'update');
    },

    render: function () {
        ...
        this.update();
        return this;
    },

    update: function() {
        this.model.fetch();
        setTimeout(this.update, 5000);
    }

    ...

當然,對update()setTimeout調用可以正常工作,因為this已正確綁定到有問題的視圖。

當我將setTimeout移到fetch的回調中時,就會出現問題,因為this現在指向了全局范圍:

    update: function() {
        this.model.fetch({ success: function() {
            // this is now global
            setTimeout(this.update, 5000);
        }});            
    }

如何實現連續(不重疊)更新功能。 或者-如何在fetch回調中將視圖的范圍應用於this

更新資料

只是討論了這個老問題,當我在這里找到_.bind OTT時,我現在就遵循這種模式以供將來參考:

    update: function() {
        var self = this;
        this.model.fetch({ success: function() {
            setTimeout(self.update, 5000);
        }});            
    }

選項之一是使用_.bind函數:

update: function() {
    this.model.fetch({ success: _.bind(function() {
        setTimeout(this.update, 5000);
    }, this)});            
}

我知道這是一個老問題,但是成功和失敗事件返回三個值:模型,響應和選項。 除了在成功函數中調用this.update ,您可以調用model.update

update: function() {
    this.model.fetch({ success: function( model, response, options) {
       setTimeout(model.update, 5000);
    }});            
}

暫無
暫無

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

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