简体   繁体   English

整理一个ribs.js集合?

[英]Organize a backbone.js collection?

How does one create a collection (in backbone.js) that is organized by an id. 一个人如何创建一个由id组织的集合(在ribs.js中)。 For example I would think it's quite common that collections need to be organized by date, category, keyword, type the list goes on. 例如,我认为通常需要按日期,类别,关键字和列表类型来组织集合。 In my case I am trying to find an elegant way to organize players to team. 就我而言,我正在尝试寻找一种优雅的方式来组织球员与团队。

I don't think I need a plugin for this, my goal is just to organize the players to be grouped inside a div while using one clean json file so I can have a nice organized list. 我认为我不需要插件,我的目标只是使用一个干净的json文件将播放器分组到一个div中,以便我可以有一个很好的组织列表。 Again ideally it would be nice to use one json file for this, and structure the HTML similar to how the json itself is structured in terms of nesting, in my example league being the parent of everything, then team being the parent of the players . 同样理想情况下是很好用这一个JSON文件,结构HTML相似,如何JSON本身在嵌套方面的结构,在我的例子league是一切的父母,然后team是的父players

I have gone through many backbone tutorials multiple times, and understand the flow and syntax pretty comfortably, but all tutorials work with one collection outputting a simple list in no specific order. 我已经多次阅读了许多主干教程,并且相当轻松地理解了流程和语法,但是所有教程都与一个集合一起工作,并以没有特定的顺序输出一个简单的列表。

Basically I want to be able to create a clean json array like below. 基本上,我希望能够创建一个干净的json数组,如下所示。 Then turn it into nice organized HTML. 然后将其转换为组织良好的HTML。

{
  "league":
       [{
        "team":"Lakers",
        "players": [
                {
                    "name": "Kobe"
                },
                {
                    "name": "Steve"
                }
        ]
        },
        {
        "team":"Heat",
        "players": [
                {
                    "name": "LeBron"
                },
                {
                    "name": "Mario"
                }
        ]
        }]

}    

So this json structure is valid but it's not one I have used it's nested a little bit more, so accessing the models requires a little different technique, I am hoping to learn if this kind of array is ideal? 因此,这种json结构是有效的,但不是我使用过的嵌套结构,因此访问模型需要一些不同的技术,我希望了解这种数组是否理想? Also if so how would I group say Kobe , Steve inside a div with perhaps the class name Lakers whilst obviously separating it from LeBron and Mario keeping those two inside a div with again perhaps a class of Heat . 同样如果我是这样的话,我怎么说KobeSteve在一个也许叫Lakers的班级里,而显然将它与LeBronMario分开呢,保持这两个人在一个div里又可能是一个Heat

Another example I could use would be like a actors to movies collection, again is the json format ideal (seems like it to me) here I obviously group actors to their respected movie? 我可以使用的另一个例子是演员收藏电影,同样,json格式是理想的(对我来说似乎很像),在这里我显然将演员归类为他们所钟爱的电影吗? I would greatly appreciate some tips on building a clean view or views with a template or templates for outputting this nice and tidy. 我将不胜感激有关构建一个或多个干净视图或使用一个或多个模板来输出此整洁视图的一些技巧。

{
  "movies":
       [{
        "title":"Prisoners",
        "actors": [
                {
                    "name": "Hugh Jackman"
                },
                {
                    "name": "Jake Gyllenhaal"
                }
        ]
        },
        {
        "title":"Elysium",
        "actors": [
                {
                    "name": "Matt Damon"
                },
                {
                    "name": "Jodie Foster"
                }
        ]
        }]

}

Again just working with this json data and backbone.js how do I create a maintainable view for this array? 同样,仅使用此json数据和ebrian.js,如何为该数组创建可维护的视图?

Final Note: I was able to successfully group players to teams using two json files, and assigning a player and id that matched the team id, then looped the team collection with the player collection inside using where to organize it (I am trying to rethink this better). 最后说明:我能够使用两个json文件成功地将玩家分组到团队中,并分配与团队ID相匹配的玩家和ID,然后将团队集合与玩家集合循环到内部,并where进行组织(我想重新思考一下)这个更好)。 To me this is not taking advantage of backbone, it can get confusing and just seems wrong to me. 对我来说,这没有利用主干网,这会造成混乱,对我来说似乎是错误的。 So again I hope to improve my knowledge here and get better. 因此,我再次希望在这里提高自己的知识并变得更好。 I would immensely appreciate clear concise information, I really struggle to wrap my head around this topic :) 我将非常感谢您提供简洁明了的信息,我真的很难解决这个问题:)

THANKS!! 谢谢!!

Keep your JSON in a Backbone friendly structure, this will mean your models are easily organised once they are placed into the collection. 将您的JSON保持在Backbone友好的结构中,这意味着一旦将模型放入集合中就可以轻松组织它们。

JSON example JSON范例

[
    { league : 1, team : 'lakers', player : 'kobe' }
    { league : 1, team : 'lakers', player : 'steve' }
    // And so on
]

Consider that most backbone collections are built via a RESTful JSON api this would be easy to fetch directly into a collection and then sorted. 考虑到大多数主干集合都是通过RESTful JSON API构建的,因此可以很容易地直接将其提取到集合中然后进行排序。 The comparator() function on the collection is run each time a model is added to the collection, or when you ask for it to run. 每次将模型添加到集合中时,或者在您要求运行模型时,都会运行集合上的comparator()函数。

Backbone collection example 骨干收集示例

var Players = Backbone.Collection.extend({

    initialize : function() {
        // Grab the JSON from the API
        // this.fetching is now a deferred object
        this.fetching = this.fetch();
    }

    // Comparator example one, as a string
    comparator : 'team',

    // Comparator example two, as a function
    comparator : function(model) {
        return model.get('team');
    }

});

The comparator as a function approach is obviously better suited to more complex sort algorithms, otherwise the comparator as a string approach would be better. 比较器作为函数方法显然更适合于更复杂的排序算法,否则比较器作为字符串方法会更好。 Bear in mind that the function approach, though a string can be returned (such as above), -1 or 1 would be better return values to indicate it's sort position. 请记住,函数方法虽然可以返回字符串(例如上面的字符串),但最好使用-11来返回值以指示其排序位置。

Comparator example with model comparison 比较器示例与模型比较

comparator : function(modelA, modelB) {
     var teamA = modelA.get('team'),
         playerA = modelA.get('player'),
         teamB = modelB.get('team'),
         playerB = modelB.get('player');

     if (teamA < teamB) { // string comparison
         return 1;
     } else if (playerA < playerB} {
         return 1;
     } else {
         return -1;
     }
}

Now whenever a model is added to the collection it is sorted into it's correct location, if using the last example, by team and then by player name. 现在,每当将模型添加到集合中时,如果使用最后一个示例,则按团队然后按玩家名称将其分类到正确的位置。

Simple view example using the collection 使用集合的简单视图示例

var ViewExample = Backbone.View.extend({

    el : "#example-container",

    render : function() {

        var self = this;

        // Use the deffered object to make sure models are
        // all available in the collection before we render
        this.collection.fetching.done(function() {

            self.collection.each(function(model) {

                self.$el.append('<p>' + model.get('player') + '</p>');

            });

        });

        return this;
    }
});

// Create the view and pass in the collection
// that will immediately fetch it's models
var view = new ViewExample({
    collection : new Players()
});

Code here is untested 这里的代码未经测试

Start by building a working model of your data. 首先建立数据的工作模型。 Your JSON suggests a hierarchy : a collection of teams that each have a collection of players. 您的JSON建议一个层次结构:一组团队,每个团队都有一组玩家。 Here's a possible implementation : 这是一个可能的实现:

var Player = Backbone.Model.extend();
var Players = Backbone.Collection.extend({
    model: Player
});
var Team = Backbone.Model.extend({
    constructor: function(data, opts) {
        // I like my subcollections as attributes of the model
        // and not on the settable properties
        this.players = new Players();

        Backbone.Model.call(this, data, _.extend(opts, {parse: true}));
    },
    parse: function(data) {
        // Players are handled in a subcollection
        if (_.isArray(data.players))
            this.players.reset(data.players);

        // They are removed from the model properties
        return _.omit(data, 'players');
    }
});
var Teams = Backbone.Collection.extend({
    model: Team,
    parse: function(resp) {
        return resp.league;
    }
});

Now you can create your root collection. 现在您可以创建根集合。 Note that you could also fetch it instead of instantiating it with the data. 请注意,您也可以fetch它,而不用数据实例化它。

// teams list
var teams = new Teams(data, {parse: true});

// for example, to get all players in all teams
var allplayers = _.flatten(teams.map(function(team) {
    return team.players.models;
}));
console.log(_.invoke(allplayers, 'get', 'name'));

And a demo : http://jsfiddle.net/8VpFs/ 和演示: http : //jsfiddle.net/8VpFs/

Once you have your structure in place, you can worry about rendering it. 一旦结构就位,就可以担心渲染它。 Let's imagine you have this (Underscore) template 假设您有这个(下划线)模板

<ul>
  <% _(teams).each(function(team) { %>
      <li><strong><%= team.team %></strong>
        <ul>
          <% _(team.players).each(function(player) { %>
              <li><%= player.name %></li>
          <% }); %>
        </ul>
    </li>
  <% }); %>
</ul>

You can alter your Team model to output a serialized representation of you model: 您可以更改Team模型以输出模型的序列化表示形式:

var Team = Backbone.Model.extend({
    // ... as before

    toJSON: function() {
        var json = Backbone.Model.prototype.toJSON.call(this);
        json.players = this.players.toJSON();
        return json;
    }
});

and render your template 并渲染您的模板

var tpl = _.template($('#tpl').html());
var html = tpl({
    teams: teams.toJSON()
})
$('body').append(html);

This usually would go into a view. 这通常会进入视图。

http://jsfiddle.net/8VpFs/1/ http://jsfiddle.net/8VpFs/1/

With a fetch fetch

var teams = new Teams();
teams.fetch().then(function() {
    var tpl = _.template($('#tpl').html());
    var html = tpl({
        teams: teams.toJSON()
    });
    $('body').append(html);
});

http://jsfiddle.net/8VpFs/2/ http://jsfiddle.net/8VpFs/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM