主页/客队有一个在backbone.js应用程序内的玩家列表?

时间:2013-11-27 02:13:01

标签: javascript jquery backbone.js

:一种。我现在处于什么水平:介绍 我刚从“Jeffery Way”完成了backbone.js课程。我正在掌握它,但我如何建立一个应用程序,说有4支球队(橙色,蓝色,绿色,黄色),然后每队5-8名球员?


B中。描述代码:以下是代码。我有 App.Models.Player 模型, App.Views.HomePlayer App.Views.AwayPlayer 视图,然后有一个< strong> App.Collections.PlayersList 集合,然后是 App.Views.Players 的集合视图,它将每个播放器模型显示为列表,我呈现相同的集合 {{家庭播放器视图中的1}} 和远端玩家视图。我不确定如何将他们与团队联系起来?我是否创建了两个集合,我不想创建太多的集合或太多的视图,我正在试图弄清楚如何使这个尽可能小和可读,我需要一些方向:)!


℃。要求:这里没有什么特别的东西,我需要一个4队的名单,然后每队5-8名队员(总共约20-25名队员,然后需要将他们与特定队伍联系起来)我需要确定目前选定的球队无论是主场还是客场。主队和客场球队是可以互换的,我想在两侧都有一个相同球队的名单并隐藏它们,然后显示当前正在比赛的球队,我只是不确定是否有比是什么?

最后一句话:是的我正在使用players = new App.Collections.PlayersList在chrome的console.log中进行测试..当我获得一些动力时它将被删除。

window

请提出任何问题,获得一些洞察力并最终开展真实世界的项目真是太酷了,这对于大多数简单点来说都很有趣!

谢谢!

编辑更新的数组:我可以安排我的阵列吗?如果是这样,这会改变模型,这是有效的,我该如何实现呢?任何链接..建议这将是很酷的,我不会创建一个我不会想到的新集合。这真的很新,所以任何提示都会让人感到安慰。

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>

    <h1>You have arrived.</h1>
    <div class="app">
        <button type="button"class="add">ADD</button>
    </div>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="http://underscorejs.org/underscore.js"></script>
    <script src="http://backbonejs.org/backbone.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/backbone-localstorage.js/1.1.0/backbone.localStorage-min.js"></script>

    <!-- Templates -->
    <script type="text/template" id="home-template">
        <div style="float: left; width: 47%;">Name: <%= name %> - Points: <%= points %><button class="btn"></button></div>
    </script>

    <!-- Templates -->
    <script type="text/template" id="away-template">
        <div style="float: right; width: 47%;">Name: <%= name %> - Points: <%= points %><button class="btn"></button></div>
    </script>

<script>
$(function(){

    //Name spacing
    window.App = {
        Models: {},
        Collections: {},
        Views: {},
        Router: {}
    };


/*** OUR MODEL OF A PLAYER... PLAYER MODEL then SINGLE PLAYER VIEW ***/

    // Player Model
    // ----------

    // Our **Player** model has `name`, `points`, and `rebounds` attributes.
    window.App.Models.Player = Backbone.Model.extend({
        // Default attributes for the player item.
        defaults: {
            name: "Michael",
            points: 10,
            rebounds: 9
        }

    });

    // Single player view
    // ---------------

    // This is a view of how a player should look.
    window.App.Views.HomePlayer = Backbone.View.extend({

        //el is a list tag.
        tagName:  "li",

        // Cache the template function for a single item.
        template: _.template($('#home-template').html()),

        events: {
            'click .btn': 'mikeAlert'
        },

        mikeAlert: function() {
           alert('get food');
        },

        // Re-render the titles of the todo item.
        render: function() {
          this.$el.html( this.template( this.model.toJSON() ) );

          return this;
        }

    });

    // Single player view
    // ---------------

    // This is a view of how a player should look.
    window.App.Views.AwayPlayer = Backbone.View.extend({

        //el is a list tag.
        tagName:  "li",

        // Cache the template function for a single item.
        template: _.template($('#away-template').html()),

        events: {
            'click .btn': 'mikeAlert'
        },

        mikeAlert: function() {
           alert('get food');
        },

        // Re-render the titles of the todo item.
        render: function() {
          this.$el.html( this.template( this.model.toJSON() ) );

          return this;
        }

    });

/*** END PLAYER MODEL SETUP ***/



/*** OUR PLAYERS COLLECTION... PLAYERS COLLECTION then PLAYERS COLLECTION VIEW ***/

    // Players Collection
    // ---------------

    // We connect the players collection to the player model
    // The collection of players is backed by *localStorage* instead of a remote
    // server.
    window.App.Collections.PlayersList = Backbone.Collection.extend({

        // Reference to this collection's model.
        model: App.Models.Player

        // Save all of the player items under the `"players-backbone"` namespace.
        //localStorage: new Backbone.LocalStorage("players-backbone"),

    });


    // Players Collection View
    // ---------------

    // Display a list of all player*s* here.
    window.App.Views.Players = Backbone.View.extend({
        // Instead of generating a new element, bind to the existing skeleton of
        // the App already present in the HTML.
        el: $(".app"),

        initialize: function() {
            this.render();
        },

        render: function() {

            this.collection.each(this.addOne, this);

            return this;
        },

        addOne: function(model) {

            //Create a new child view
            var homeplayer = new App.Views.HomePlayer({ model: model });
            var awayplayer = new App.Views.AwayPlayer({ model: model });

            //Then append it to the root, this
            this.$el.append( homeplayer.render().el );
            this.$el.append( awayplayer.render().el );
        }

    });

/*** END PLAYER*S* COLLECTION SETUP ***/


    // Dummy Collection, new instance of *App.Collections.PlayersList* 
    // ---------------
    window.players = new App.Collections.PlayersList([
        {
            name: 'McGee',
            points: '14'
        },
        {
            name: 'Joe E',
            points: '21'
        },
        {
            name: 'Mike',
            points: '8'
        }
    ]);



    //Create new instaces to initialize each view

    // New *App.Views.Player* instance, need to instantiate to set the model in the view.
    // ------------
    window.playersView = new App.Views.Players({ collection: players });


});
</script>

</body>
</html>

所以我猜测而不是创建一个新的集合/模型等我可以添加玩家团队名称,然后在一个类中添加团队名称,只显示特定团队和它的玩家..这里是jSON数组。如果有更好的方法,请解释我正在学习并掌握骨干以获得更好的开发人员工具。

{
    "team":
        {
            "blue":
                [
                    { "name": "Mike", "points": 10 },
                    { "name": "Joe", "points": 13 },
                    { "name": "Kobe", "points": 23 }
                ]
        },

},
{
    "team":
        {
            "orange":
                [
                    { "name": "John", "points": 12 },
                    { "name": "Narlens", "points": 33 },
                    { "name": "MJ", "points": 22 }
                ]
        },

}

1 个答案:

答案 0 :(得分:1)

修改

添加了jsfiddle: http://jsfiddle.net/ythLm/

不确定这是否是您想要实施的内容。我在本演示中将球员分配给球队,这可能会也可能不会满足您未来的所有要求。 (但我们总能改进):)

===原始答案===

我不确定我在这里完全理解你的要求......所以你想在一个视图中显示所有玩家?并显示他们的球队名称和方面?什么是球员名单的顺序?

但:

将玩家分配给团队,您只需将其作为团队模型的属性传递即可。

哦,是的,我认为你需要一个团队模型:

App.Models.Team = Backbone.Model.extend({
    //team stuff
});

App.Collections.Teams = ... //usually you want a collection too

然后

var blueTeam = new App.Models.Team({
  name: 'blue team',
  players: new App.Collection.Players([
    {"name": "Mike", "points": 10 },
    { "name": "Joe", "points": 13 },
    { "name": "Kobe", "points": 23 }
  ]);
});

主队和客队,或者只是当前选定的球队,可以只是球队模型的一个属性。如果要更改它们,只需更改团队模型的属性即可。例如

var blueTeam = new App.Models.Team({
  //other attributes and players
  selected: true,
  side: 'home'
});

您也可以将这些状态附加到收藏中,但我不建议这样做。 (让我们想一想,如果这是一个真实世界的应用程序,Team has_many:玩家,玩家属于:团队)

但是你想让所有玩家都在一个列表中(如果我理解你的要求正确的话),所以我们需要为每个玩家分配团队,而不是将玩家分配给团队:

var mike = new App.Models.Player({
  name: 'mike',
  team: new App.Models.Team({
    name: 'blue'
  });
});

但是这有一个问题:有20个玩家,但只有4个团队,你将让每个团队重复5次,他们都是不同的对象。例如。如果你这样做

mike.get('team').set('selected', true);
只有迈克的团队&#39;将被选中,其他蓝队球员&#39; &#34;队&#34;将不会更新。

解决这个问题。

首先,完全获得所有玩家。记住,他们需要一个外键,或者对他们所属的团队的任何形式的引用:(可能是team_id,或者只是team_name)

var players = App.Collections.PlayersList([
    {"name": "Mike", "points": 10, team_id: 1},
    {"name": "Joe", "points": 13, team_id: 2},
    {"name": "Kobe", "points": 23, team_id: 1}
    //... all your players
]);

然后,你的团队,但你不必分配球员:

var teams = new App.Collections.Teams([
  {"id": 1, name: "blue team", selected: false, side: ''},
  {"id": 2, name: "red team", selected: false, side: ''}
  //... all your teams
]);

现在,您应用中的某个位置会将球队分配给您的球员:

players.each(function(player){
  player.set("team", teams.get(player.get("team_id")));
});
这样做,确保同一团队中的所有玩家都拥有相同的团队模型。

(示例http://jsfiddle.net/sbjaz/10/当调试器暂停代码时,打开控制台,尝试使用player_1,player_2和player_3,1和2在同一个团队中,尝试更改团队中的任何属性玩家1/2的模型并检查另一个团队模型)

(另一个示例http://jsfiddle.net/sbjaz/11/执行相同的操作,当您更新team_1的球队时,您会注意到,球员_2的球队未更新)

最后,在您的收藏视图中:

addOne: function(model) {
  var playerView;
  if(model.get("team").isHomeTeam()) {  //isHomeTeam is a helper method in team model
    playerView = new App.Views.HomePlayer({ model: model });
  } else {
    playerView = new App.Views.AwayPlayer({ model: model });
  }
  this.$el.append( playerView.render().el );
}

嗯,你需要将Teams集合传递给PlayerList视图,以便你知道团队中是否有任何变化:

new playersView = new App.Views.Players({ 
  collection: players,
  teams: teams
});

在视图定义中跟踪团队更改:

App.Views.Players = Backbone.View.extend({
  initialize: function(options) {
    this.teams = options.teams;
    this.teams.on('change', this.render, this);  //if any of the team changes, rerender everyting
    this.render();
  }
});
而且,你可能会认为,这根本没有效率:每次你回到Home / Away球队时,所有球员都必须重新渲染。我该如何重构这个?

首先,我认为你不必为玩家视图定义两个视图 - 他们有太多的重复代码!它不干。

让我们定义一个适用于任何玩家的视图(至少目前为止):

App.Views.PlayerView = Backbone.View.extend({
  tagName:  "li",

  // events...mikeAlert they are all the same
  // you will see why we assign this.template in render instead of initialize
  //well or you don't have to assign this.template at all.
  render: function() {
    var templateSelector = this.model.isHomeTeam() ? "#home-template" : "#away-template"; 
    this.template = _.template($(templateSelector).html());

    return this.$el.html(this.template(this.model.toJSON());;
  }
});

你明白了,或者如果他们有太多的重复代码,你甚至不必写两个模板!

你需要更新addOne:

//since PlayerView's render() returns html directly...

addOne: function(model) {
  this.$el.append(new App.Views.PlayerView({model: model}).render());
}

现在发生的事件,您不必将团队传递给您的PlayersView或将收集更改事件绑定到那里。

在您的PlayerView初始化中:

  initialize: function() {
    //rerender player view, when team is changed!
    this.model.on('change', this.render, this);
  }

现在,每次更换任何团队时,只会更新相关的playerViews。