jma*_*mav 8 backbone.js marionette
我想从参数中获取特定网址的模型:url:server/somecontroller/id /?type = gift
简单的工作方式是:
collection.fetch({ data: { type: 'gift'} });
Run Code Online (Sandbox Code Playgroud)
但我想在模型中设置它:
...
if(id){
App.coupon = new AffiliatesApp.Coupon({id: id});
} else {
App.coupon = new AffiliatesApp.Coupon({id: 'somecontroller'}, {type: 'gift'});
}
App.coupon.fetch();
Run Code Online (Sandbox Code Playgroud)
我怎样才能实现它?
实现此目的的最简单方法是使用您定义的优惠券模型覆盖Backbone的url方法.例如,您可以这样做:
Affiliates.Coupon = Backbone.Model.extend({
urlRoot : "server/somecontroller/",
url : function(){
var url = this.urlRoot + this.id;
if(this.get("type")){
url = url + "/?type=" + this.get("type");
}
return url;
}
});
Run Code Online (Sandbox Code Playgroud)
此解决方案易于实现,但有一个缺点:生成的URL将用于与服务器同步的每个操作(fetch,save,..).
如果您需要根据正在执行的操作更好地控制URL的生成,则需要为模型覆盖Backbone的Sync方法.