2013-12-15 28 views
2

我正在嘗試在我的應用程序中創建一個User.current(),該應用程序使用$.getJSON('/users/current', function(data) { ... });從我的服務器中提取數據。我使用的話語使用辛格爾頓方法,它具有以下功能:如何返回延期承諾並使用Ember.Deferred創建模型?

Dashboard.Singleton = Ember.Mixin.create({ 
     // See https://github.com/discourse/discourse/blob/master/app/assets/javascripts/discourse/mixins/singleton.js 

     current: function() { 
       if (!this._current) { 
         this._current = this.createCurrent(); 
       } 
       return this._current; 
     }, 

     createCurrent: function() { 
       return this.create({}); 
     } 
}); 

在我User單模式,我已經重寫createCurrent如下:

Dashboard.User.reopenClass(Dashboard.Singleton, { 
     createCurrent: function() { 
       return Ember.Deferred.promise(function(p) { 
         return p.resolve($.getJSON('/users/current').then(function(data) { 
           return Dashboard.User.create(data); 
         })); 
       }); 
     } 
}); 

用戶是一個正常的餘燼對象型號:

Dashboard.User = Ember.Object.extend({ 

}); 

這確實從服務器請求數據,但功能沒有正確設置User.current() - 當我檢查它時,User.current()沒有應設置的屬性,例如name

如何返回並設置當前用戶使用Ember的延期和承諾?

+0

什麼是用戶模式?普通的灰燼物體? – Kingpin2k

+0

是的。我會用什麼'User'來更新我的問題。 – josh

回答

0

這就是因爲你要代替用戶返回承諾。

爲什麼不創建用戶,然後再填寫屬性。

或使用灰燼數據應用(許諾可以作爲一次解決的對象)

DS.PromiseObject = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin); 

function promiseObject(promise) { 
    return DS.PromiseObject.create({ promise: promise }); 
} 
+0

不應該返回用戶將被退回的承諾嗎? – josh

+0

如果你想,但是你將永遠不得不使用promise.then訪問模型(function(record){//這裏是}})); – Kingpin2k

+0

這可能是你想要的,如果你總是想等到用戶定義 – Kingpin2k

0

由於$ .getJSON(「/用戶/電流」)返回一個承諾的承諾代理模式,可能以及使用它。

createCurrent: function() { 
       return $.getJSON('/users/current').then(function(data) { 
         return Dashboard.User.create(data); 
       }); 
    } 

然後,你需要記住,createCurrent返回一個承諾,而不是對象本身,所以你將需要:

current: function() { 
      if (!this._current) { 
        var that = this; 
        this.fetching = true; 
        this.createCurrent().then(function(val) { 
         that.fetching = false; 
         that._current = val; 
        }); 
      } 
      return this._current; 
    }, 
+0

目前將返回undefined,直到承諾解決爲止,此代碼不會異步運行。 – Kingpin2k

+0

我知道在承諾解決之前,當前狀態將不確定。爲什麼這是個問題?指的是它不會異步運行? – RHollister

+0

因爲,無論何時您調用this.current(),您都會創建一個新實例,並創建一個新的ajax調用,直到它解析爲止,並且您將不斷返回undefined。 – Kingpin2k