1

我正在尝试为需要使用 Backbone.js 和 RESTful 架构克隆资源(本例中为请求)的场景找出最佳方法。

当用户克隆某些资源时,应该会出现一个对话框,他可以在其中为请求键入新名称并设置新的 DeadlineDate,所有其他字段必须从另一个请求中克隆。出现在对话框中的名称应该类似于Request Name (Clone 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();
    }
});

这是克隆如何工作的工作流程:

  1. 用户单击克隆。
  2. 发出请求以获取具有 url 参数的资源clone: true。这将返回请求名称附加Clone 'Clone Number'
  3. 将打开一个对话框,用户可以在其中输入一些数据。
  4. 将创建一个没有 Id 的新模型,并使用父请求设置一个新属性。例如:ClonedFromRequestId: 123
  5. 此新模型​​已保存。

我不知道这是否是这种情况的最佳做法。

4

0 回答 0