2012-09-04 22 views
1

我正在使用Backbone js創建應用程序,如服務。每個應用程序都有一個user_id和一個已設置的application_id。每次主幹調用fetch(),save()或其他RESTful/ajax函數時,我都希望user_id和application_id自動與模型數據一起傳遞。在BackBone模型中自動傳遞Certian值Ajax函數

我知道我將不得不擴展骨幹模型,然後確保我所有的模型都是從這個模型擴展而來,但是我該如何修改以及如何調用父模型?

的僞例(不是很確定)

MyModel = Backbone.Model.extend({ 
    save : function(data) { 
     data.application_id = 3; 
     data.user_id = 5; 
     parent.save(data); 
} 
}); 

Scores = MyModel.extend({ 
     default : { 
     score : 0 
} 
}); 

//This should automatically grab the application id and user id 
scores = new Scores(); 
scores.set('score', 5); 
score.save() 

如何正確地做到這一點?通過完成,我的意思是代碼中的一個點可以用於save(),fetch()和destroy()?

回答

3

如何修改您的Backbone同步?如果你確定要通過user_idapplication_idsave() fetch() and destroy()每一個模型,那麼你可以做這樣的事情。我相信

/* alias away the sync method */ 
Backbone._sync = Backbone.sync; 

/* new Backbone.sync method */ 
Backbone.sync = function(method, model, options) { 

    // For example purpose, this will only run on POST, PUT, and DELETE requests 
    // If you want you can also set it for method == 'read' for your fetch() 

    if (method == 'create' || method == 'update' || method == 'delete') { 
     model.set('user_id', userID); 
     model.set('application_id', appID); 
    } 

    /* proxy the call to the old sync method */ 
    return Backbone._sync(method, model, options); 
}; 

我做這樣的事情對我的CSRF令牌檢查,以防止交叉網站註冊僞造。除了操縱模型之外,我確保所有POST,PUT和DELETE請求都有一個特殊的X-CSRF標頭和我的唯一標記。

+0

我一直在尋找的確切答案!也適用於收藏。謝謝。 –

0

如果你的價值觀(應用標識和用戶ID)是預先確定的,你可以在你的模型initialize方法做到這一點

MyModel = Backbone.Model.extend({ 
    this.set('application_id', appID); 
    this.set('user_id', userID); 
}); 

這些值現在是模型的一部分,因此每一個CRUD操作的一部分。