我正在尝试找出使用Backbone.js和RESTful架构克隆资源(本例中为Request)的场景的最佳方法。
当用户克隆某些资源时,应该出现一个对话框,在该对话框中可以为Request键入新名称并设置新的DeadlineDate,所有其他字段必须从其他Request中克隆。对话框中显示的名称应类似于请求名称(克隆1),其中数字应为已创建的副本数。
以下代码表示我的设计方式:
var RequestModel = Backbone.Model.extend({
url: '/path/to/request',
idAttribute: "Id",
defaults: {
Name: '',
DeadlineDate: '',
// loads of other options
Content: '',
Documents: []
TeamMembers: []
}
})
// Request View
var RequestView = Backbone.View.extend({
events: {
'click .btn-clone': 'clone'
},
clone: function(e){
var id = $(e.target).closest('.request').data('request-id'),
referenceModel = new RequestModel({ Id: id });
// with the clone true param the server should append
// to the Name of the Request: (Clone *Number*)
referenceModel
.on({ 'sync': this.renderCloneDialog }, this)
.fetch({ data: { clone: true } });
},
renderCloneDialog: function(model){
// create a brand new instance of the model
// with the previous values
var clonedRequest = model.toJSON();
clonedModel = new RequestModel( _.omit(clonedRequest, 'Id') );
// send the cloned from id so the server use as reference
clonedModel.set('ClonedFromRequestId', clonedRequest.get('Id'));
var clonedRequestDialog = new CloneRequestDialogView({
model: clonedModel
});
}
});
// Request View
var CloneRequestDialogView = Backbone.View.extend({
// the method for saving will be just saving
saveClone: function(){
// update data based on the form
// and save the model
this.model.save();
}
});
这是克隆工作方式的工作流程:
clone: true
获取请求。这将返回附加克隆'克隆Numnber'。ClonedFromRequestId: 123
。我不知道这是否是这种情况的最佳做法。