2013-02-17 64 views
10

我像這樣綁定了我的主幹模型的變化事件。如何知道Backbone model.fetch()完成的時間?

this.model.on("change", this.render, this); 

有時候我想獲取最新版本的模型並強制渲染視圖。所以我這樣做

this.model.fetch(); 

不幸的是,如果新數據與先前存儲在模型中的數據不同,model.fetch()只會觸發change事件。

如何在抓取完成時始終觸發this.render回調,無論是否觸發更改事件?

感謝(提前)對你的幫助

回答

11

您可以使用$.ajax成功回調,但您也可以只聽聽模型上的Backbone syncerror事件。 sync成功調用服務器後觸發,error在調用服務器失敗後觸發。

this.model.on('sync', this.render, this); 
this.model.on('error', this.handleError, this); 
1

fetch方法選擇性地接受具有成功和錯誤回調;最簡單的解決方案是將您查看的render放入成功回調中。你也可以使用返回的jqXHR promise,但是如果有AJAX成功(每個jQuery)但模型初始化失敗的情況,那麼這種用法可能會有問題。

1

我不知道什麼是你的代碼結構,但是如果你只是抓取您的視圖中你的模型,你可以使用類似這樣

var that = this; 
this.model.fetch().done(function() { 
    that.render(); 
}); 

否則,如果你是獲取你的模型你的視野之外,你可以通過你的承諾,你的觀點,並做出類似

var promise = model.fetch(); 
// other code here 
var view = new View({ 
    model: model, 
    promise: promise 
}); 

和視圖裏面的東西,例如,在初始化

View = Backbone.View.extend({ 
    initialize: function(){ 
     this.options.promise.done(function() { 
      // your code here 
     }); 
    } 
}); 
1

這個怎麼樣的解決方案:

// emit fetch:error, fetch:success, fetch:complete, and fetch:start events 
fetch: function(options) { 
    var _this = this; 

    options = options || {}; 

    var error = options.error; 
    var success = options.success; 
    var complete = options.complete; 

    options.error = function(xhr, textStatus, errorThrown) { 
    _this.trigger('fetch:error'); 
    if (error) error(xhr, textStatus, errorThrown); 
    }; 

    options.success = function(resp) { 
    _this.trigger('fetch:success'); 
    if (success) success.call(options.context, resp); 
    }; 

    options.complete = function() { 
    _this.trigger('fetch:complete'); 
    if (complete) complete(); 
    }; 

    _this.trigger('fetch:start'); 

    return Backbone.Model.prototype.fetch.call(this, options); 
} 

鏈接要點https://gist.github.com/fedyk/23761ce1236c5673fb84

相關問題