【问题标题】:Getting a collection based on a foreign key i.d. with Backbone.js获取基于外键 ID 的集合使用 Backbone.js
【发布时间】:2013-07-29 09:34:52
【问题描述】:

我正在创建我的第一个主干应用程序。它只是一个球队和他们的球员的名单。我可以显示团队列表。但是我在展示那支球队的球员时遇到了问题。

我的 Player 模型如下:

定义(函数(要求){

"use strict";

var $                   = require('jquery'),
    Backbone            = require('backbone'),


    Player = Backbone.Model.extend({

        urlRoot: "player",

        initialize: function () {
            this.players = new PlayerCollection();
            this.players.url = this.url + "/" + this.team_id;
        }  

    }),

    PlayerCollection = Backbone.Collection.extend({

        model: Player,
        url: "team_players",

    });

return {
    Player: Player,
    PlayerCollection: PlayerCollection
};

});

所以 PlayerCollection 是基于 team_id 的玩家集合。

在我的路由器中:

            var playerList = new models.PlayerCollection({team_id: team_id});
            playerList.fetch();

但是当我希望 URL 为“http://mydomain.com/api/team_players/1”(其中 1 是团队 ID)时,发送的 GET URL 是“http://mydomain.com/api/team_players”。那么如何根据team_id获取集合呢?

【问题讨论】:

    标签: javascript backbone.js


    【解决方案1】:

    试试这个:

    PlayerCollection = Backbone.Collection.extend({
    
        model: Player,
        url: function(){
           return "team_players/" + this.team_id;
        }
    
    });
    

    //像这样使用它

     var playerList = new models.PlayerCollection();
     playerList.team_id = team_id;
     playerList.fetch();
    

    【讨论】:

      猜你喜欢
      • 2011-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-01
      • 1970-01-01
      • 2020-06-14
      • 1970-01-01
      相关资源
      最近更新 更多