2011-07-04 30 views
1

我試圖讓我的頭在sproutcore數據源和相關模型,我不知道快如果有人可能會幫我理解這一切更好。Sproutcore數據源和創建與關係的新記錄

基本上我有兩個相關的模型客戶端和品牌,客戶可以有很多品牌和品牌可以有一個客戶端,我已經正確定義了我的模型,一切都按預期拉回來了。我遇到的問題是如何創建一個新的品牌並建立它的關係。 所以我的品牌控制器上我有一個像createBrand方法,以便:

var brand = DBs.store.createRecord(DBs.Brand, { 
    title: this.get('title') 
}, Math.floor(Math.random()*1000000)); 

brand.set('client', this.get('client')); 

MyApp.store.commitRecords(); 

所以,因爲這是一個新的品牌我隨機生成一個新的ID(的第二個參數createRecord)。這是在我的數據源中調用我的createRecord來創建新品牌,然後它還爲客戶端調用updateRecord。

我遇到的問題是客戶端更新正在傳遞關係中的臨時(隨機生成的ID)。我應該如何構建我的新品牌創造?我應該等待服務器返回新創建的品牌ID,然後更新客戶關係嗎?如果是的話,我會怎麼做呢?

感謝

馬克

回答

2

右鍵,坐在SproutCore的IRC頻道再跟他建議建立一個框架,以手工處理我所有的服務器交互mauritslamers後。

所以我設置了一個名爲CoreIo的框架,它包含我所有的模型,商店和數據源。 數據源僅用於從服務器即獲取記錄:

fetch: function(store, query) { 
    var recordType = query.get('recordType'), 
     url = recordType.url; 


    if (url) { 
     SC.Request.getUrl(CoreIo.baseUrl+url) 
      .header({ 'Accept': 'application/json'}) 
      .json() 
      .notify(this, '_didFetch', store, query, recordType) 
      .send(); 

     return YES; 
    } 

    return NO; 
}, 


_didFetch: function (response, store, query, recordType) { 
    if (SC.ok(response)) { 
     store.loadRecords(recordType, response.get('body')); 
     store.dataSourceDidFetchQuery(query); 
    } else { 
     store.dataSourceDidErrorQuery(query, response); 
    } 
}, 

然後CoreIo框架已經爲我的模型創建方法,即:

CoreIo.createBrand = function (brand, client) { 
    var data = brand, 
     url = this.getModelUrl(CoreIo.Brand); 

    data.client_id = client.get('id'); 

    SC.Request.postUrl(url) 
     .json() 
     .notify(this, this.brandDidCreate, client) 
     .send(data); 
}; 

CoreIo.brandDidCreate = function (request, client) { 
    var json = request.get('body'), 
     id = json.id; 

    var ret = CoreIo.store.pushRetrieve(CoreIo.Brand, id, json); 
    var brand = CoreIo.store.find(CoreIo.Brand, id); 

    if (ret) { 
     client.get('brands').pushObject(brand); 
    } 
}; 

我會再打電話到這些「動作」以創建我的新模型,這也將建立關係。

相關問題