【问题标题】:Relation between models in backbone.jsBackbone.js 中模型之间的关系
【发布时间】:2016-11-14 09:52:48
【问题描述】:

我正在寻找正确的主干结构来实现以下目标:

两个服务器 API:

  • GET api/event/4 :返回 id 为 4 的事件对象。
  • GET api/event/4/registrations : 返回属于 id 为 4 的事件的注册对象列表

我想要一个显示事件对象和注册列表的视图。

这很简单,但我不知道如何组织我的活动和注册模型。 我应该使用骨干关系吗?

我的事件模型目前是这样的: (从现在开始,该集合预计将包含接下来的 10 个事件)。

我应该如何定义我的注册模型以及如何初始化它,知道它总是在事件模型的上下文中?

var app = app || {};

app.EventModel = Backbone.Model.extend({
    urlRoot: app.API_server + 'event'
});


app.EventCollection = Backbone.Collection.extend({
    model: app.EventModel,
    url: app.API_server + 'event',
    initialize: function(){
        dt = new Date();
        start_dt = dt.toISOString();
        this.fetch({
            data: {limit:10, start_dt:start_dt},
            error: function (model, response, options) {
                if(response.status == '403') {
                    app.Session.logout();
                }
            }
        })
    }
});

【问题讨论】:

    标签: javascript backbone.js backbone-model backbone-relational


    【解决方案1】:

    为注册创建一个集合,并将url 属性用作函数。默认情况下,RegistrationCollection 的模型的urlRoot 将是集合的url 加上它们的id

    app.RegistrationCollection = Backbone.Collection.extend({
        url: function() {
            return app.API_server + 'event/' + this.id + '/registrations';
        },
        initialize: function(models, options) {
            options = options || {};
            this.id = options.id;
        }
    });
    

    然后,在EventModel 初始化时,添加RegistrationCollection 作为属性,将事件id 作为选项传递给集合。

    app.EventModel = Backbone.Model.extend({
        urlRoot: app.API_server + 'event',
        initialize: function() {
            this.registrations = new app.RegistrationCollection(null, {
                id: this.id
            });
        }
    });
    

    从初始化中删除fetch,你想让你的集合可重复使用。

    app.EventCollection = Backbone.Collection.extend({
        model: app.EventModel,
        url: app.API_server + 'event',
    });
    

    在视图或路由器内部获取,具体取决于它对您的应用更有意义的位置。

    var EventView = Backbone.View.extend({
    
        initialize: function() {
            this.collection = new app.EventCollection();
            var dt = new Date(),
                start_dt = dt.toISOString();
    
            // this should be here, outside of the collection.
            this.collection.fetch({
                data: { limit: 10, start_dt: start_dt },
                error: function(model, response, options) {
                    if (response.status === 403) {
                        app.Session.logout();
                    }
                }
            });
        },
    });
    

    【讨论】:

      猜你喜欢
      • 2012-07-01
      • 2014-08-11
      • 1970-01-01
      • 1970-01-01
      • 2013-03-27
      • 2014-12-02
      • 2012-09-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多