2013-11-27 3 views
0

농구 통계 어플리케이션을 만들고 있는데, 플레이어와 그 속성의 집합이 있습니다. 두 개의 콜렉션 결합하기 backbone.js

players = new App.Collections.PlayersList(
    [ 
     { 
      name: 'McGee', 
      points: '14' 
     }, 
     { 
      name: 'Joe E', 
      points: '21' 
     }, 
     { 
      name: 'Mike', 
      points: '8' 
     } 
    ] 
); 

그때 나는이 How to place a collection within a model in Backbone.js? 을 따라 내 팀 모델에 추가 된 팀

teams = new App.Collections.TeamsList(
    [ 
     { 
      team: 'Green', //Accidentally used uppercase, will change that, just didnt want to confuse you because it's uppercase in the console.log picture below 
     }, 
     { 
      team: 'Blue', 
     } 
    ] 
); 

의 목록을 가지고있다.

App.Models.Team = Backbone.Model.extend({ 
    // Default attributes for the player item. 
    initialize: function() { 
     // assuming Players a collection of players 
     console.log(this.set('players', new App.Collections.PlayersList)); 
    } 

}); 

콘솔에는 두 모델이 모두 표시되지만 플레이어는 비어 있습니다.

enter image description here

이 난 그냥 멍청한 놈 오전에 접근하는 방법을 모르고 :

나는이 같은 결과를 얻으려고 노력하지하고 있고, 몇 가지 큰 복잡한 문제가되지 않습니다. 사실 이것은 선수를 팀에 붙이는 데 어려울 수 있습니다. 어떻게이 선수들이이 팀에 있다고 말할 수 있습니까?

<div class="green"> 
    <li data-player="McGee">Name: McGee, Points: 14</li> 
    <li data-player="Joe">Name: Joe E, Points: 21</li> 
    <li data-player="Mike">Name: Mike, Points: 8</li> 
</div> 

// Havent created players for this yet, but you get it 
<div class="blue"> 
    <li class="">Name: McGee, Points: 14</li> 
    <li class="">Name: Joe E, Points: 21</li> 
    <li class="">Name: Mike, Points: 8</li> 
</div> 

편집 :그래서 내가 뭔가를 시도하고, 이상하지만, 지금까지의 작업 이러면는 잘하면 내가 대답을 얻을 수있는, 내 말은이 이상적입니다 아니면 더 좋은 방법이 거기에있다 확신 이것을해라, 나는 배울 것을 간청한다.

window.greenTeam = new App.Collections.PlayersList(
    [ 
     { 
      team: 'green', 
      name: 'McGee', 
      points: '14' 
     }, 
     { 
      team: 'green', 
      name: 'Joe E', 
      points: '21' 
     }, 
     { 
      team: 'green', 
      name: 'Mike', 
      points: '8' 
     } 
    ] 
); 

window.blueTeam = new App.Collections.PlayersList(
    [ 
     { 
      team: 'blue', 
      name: 'Steve', 
      points: '14' 
     }, 
     { 
      team: 'blue', 
      name: 'Eli', 
      points: '21' 
     }, 
     { 
      team: 'blue', 
      name: 'John', 
      points: '8' 
     } 
    ] 
); 

window.orangeTeam = new App.Collections.PlayersList(
    [ 
     { 
      team: 'orange', 
      name: 'Kobe', 
      points: '14' 
     }, 
     { 
      team: 'orange', 
      name: 'Lebron', 
      points: '21' 
     }, 
     { 
      team: 'orange', 
      name: 'Melo', 
      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 }); 

window.greenTeamView = new App.Views.Players({ collection: greenTeam }); 
window.blueTeamView = new App.Views.Players({ collection: blueTeam }); 
window.orangeTeamView = new App.Views.Players({ collection: orangeTeam }); 

편집 : 좋아이 하지 이상적인 롤지만, 난 당신이 코드를 본다면 내가 여기에 단어를 많이 밖으로 던지기 만하고 알고 그것을 작동, 내 전체 코드를 살펴 당신이 그것을 단순화 얼마나, 누구에게나 해결할 수있는 문제로이 퍼즐 : 귀하의 경우에는

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

    <div class="green"></div> 

    <div class="blue"></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="player-template"> 
     <div class="">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.GreenPlayer = Backbone.Model.extend({ 
     // Default attributes for the player item. 
     defaults: { 
      team: "Green", 
      name: "Michael", 
      points: 10, 
      rebounds: 9 
     } 

    }); 

    window.App.Models.BluePlayer = Backbone.Model.extend({ 
     // Default attributes for the player item. 
     defaults: { 
      team: "Blue", 
      name: "Michael", 
      points: 10, 
      rebounds: 9 
     } 

    }); 

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

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

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

     // Cache the template function for a single item. 
     template: _.template($('#player-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())); 
      this.$el.addClass(this.model.get('name')); 
      var test = this.model.get('name'); 
      return this; 
     } 

    }); 

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

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

     // Cache the template function for a single item. 
     template: _.template($('#player-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())); 
      this.$el.addClass(this.model.get('name')); 
      var test = this.model.get('name'); 
      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.GreenPlayersList = Backbone.Collection.extend({ 

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

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

    }); 

    window.App.Collections.BluePlayersList = Backbone.Collection.extend({ 

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

     // 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.GreenPlayers = 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 greenplayer = new App.Views.GreenPlayer({ model: model }); 
      $('.green').append(greenplayer.render().el); 

     } 

    }); 

    window.App.Views.BluePlayers = 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 blueplayer = new App.Views.BluePlayer({ model: model }); 
      $('.blue').append(blueplayer.render().el); 

     } 

    }); 


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


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

    window.blueTeam = new App.Collections.BluePlayersList(
     [ 
      { 
       team: 'blue', 
       name: 'Steve', 
       points: '14' 
      }, 
      { 
       team: 'blue', 
       name: 'Eli', 
       points: '21' 
      }, 
      { 
       team: 'blue', 
       name: 'John', 
       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 }); 

    window.greenTeamView = new App.Views.GreenPlayers({ collection: greenTeam }); 
    window.blueTeamView = new App.Views.BluePlayers({ collection: blueTeam }); 
    //window.orangeTeamView = new App.Views.Players({ collection: orangeTeam }); 


}); 
</script> 

</body> 
</html> 
+0

의미가 있습니까? 듣고 싶은 다른 접근 ID가 있다면 ... –

+0

이것은 누군가에게 의미가있는 것인데, 나는 플레이어를 팀에 연결 시키려고하고 있지만, 팀보기 내에서 플레이어 목록을 감쌀 필요가있다. 최종 결과는 봐야한다. 위의 게시물에서 HTML을 좋아하십시오. –

답변

2

이 많은 팀 (녹색, 파랑 등) 각 팀은 많은 선수를 가질 수있을 수 있습니다 포인트. 한 가지 방법은 TeamPlayer의 두 가지 모델을 사용하고 one-to-many 관계를 Team -> Player에서 가져 오는 것입니다. 마지막으로 TeamCollection을 만듭니다. 관계 관리를 위해 Backbone Associations을 살펴보십시오. 희망이 도움이됩니다.

+0

알겠습니다 감사합니다. 3 일 전에 백본을 말 그대로 받아 들였습니다. 그래서 OOP에서 noobie입니다. 그래서 인스턴스화하고 모든 것이 새롭지 만, 거기에 매달려 있습니다. 이것이 명확한 의미를 가지기를 바랄뿐입니다. 내 코드 :) 지금까지 일대 다 관계는 시원하게 들리지만, 제 프로젝트에 적용 할 수 있기를 바랍니다. –

+0

내가 사람을 불러 와서 이것을 사용하는 법을 배워야하기 때문에 이것을 게시하기 전에 나는 1 + 당신에게 이것을 보내기 전에 이것을 보았습니다. 그것은 처음에는 많은 일처럼 보였지만, 아픈 사람은 크게 웃었습니다. –

+0

어쨌든 당신이 간단한 예제를 제공 할 수 있습니까, 아쉽게 포인트를주었습니다. 문서를 100 % 얻지 못했습니다 ... –

관련 문제