[英]Backbone.js with a custom fetch URL
我正在嘗試在我的主干模型上設置一個變量獲取方法,該方法將獲取給定用戶的當前模型。 這可以從/api/mealplans/owner/{username}/current
上的API獲得。
我寫了以下模型。 我注釋掉了URL Root,因為原型提取調用只是使用了urlRoot
,我想看看是否覆蓋了我以某種方式傳遞的url參數。
var mealPlan = Backbone.Model.extend({
name: 'Meal Plan',
//urlRoot: '/api/mealplans',
defaults: {},
fetchCurrent: function (username, attributes, options) {
attributes = attributes || {};
options = options || {};
if (options.url === undefined) {
options.url = "/api/mealplans/owner/" + username + "/current";
}
return Backbone.Model.prototype.fetch.call(this, attributes, options);
},
validate: function (attributes) {
// To be done
return null;
}
});
我已經看到這樣做,在其他地方的某些變體中,例如在backbone.js使用不同的url進行模型保存和獲取 - 在這種情況下代碼略有不同(我從那開始並將其分解以使其更容易給我看。)
當我將它傳遞給fetch時,options對象的url參數很好,但是它似乎忽略了它!
我假設提取相同的參數以保存 - 事實並非如此。
fetch ONLY的方法簽名采用'options'而不是'attributes',因此找不到url參數。
模型代碼應該看起來更像這樣..
var mealPlan = Ministry.Model.extend({
name: 'Meal Plan',
urlRoot: '/api/mealplans',
defaults: {
},
fetchCurrent: function (username, options) {
options = options || {};
if (options.url === undefined) {
options.url = this.urlRoot + "/owner/" + username + "/current";
}
return Backbone.Model.prototype.fetch.call(this, options);
},
validate: function (attributes) {
// To be done
return null;
}
});
我認為最好覆蓋url()方法,如下所示:
var mealPlan = Ministry.Model.extend({
name: 'Meal Plan',
urlRoot: '/api/mealplans',
//--> this gets called each time fetch() builds its url
url: function () {
//call the parent url()
var url=Backbone.Model.prototype.url.call(this);
//here you can transform the url the way you need
url += "?code=xxxx";
return url;
}
...
此外,在上面的示例中,我認為存在錯誤,您應該通過fetch替換fetchCurrent
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.