charlyebrown / five-two

0 stars 0 forks source link

Add a Model AND a collection to a User #3

Closed charlyebrown closed 10 years ago

charlyebrown commented 10 years ago

I have a user who has events but I want to be able to display the user's information as well as the individual event information. How would I add both?

User Model

App.UserModel = Backbone.Model.extend({
  urlRoot: '/users',
  initialize: function(){
    console.log('New User Model Created');
  }

})```

<strong>User View</strong>
``` App.UserView = Backbone.View.extend({
  el: '#user-display',

  initialize: function(){
    console.log('User View Generated');

    this.listenTo(this.collection, 'add', this.addOne);
    this.listenTo(this.collection, 'reset', this.addAll);
    this.template = HandlebarsTemplates['users/user'];
    this.render();
  },

  render: function(){
    this.$el.html(this.template(this.model.toJSON()));
  }, ```

<strong>Router</strong>
```App.Router = Backbone.Router.extend({
  routes: {
    '': 'index',
    'events/new': 'newEvent',
    'events/edit': 'editEvent'
  },

  initialize: function(){
    console.log('New Router created');
    App.eventCollection = new App.EventsCollection();
    App.userView = new App.UserView({collection: App.eventCollection});
  },

  index: function(){
    console.log('fired index!')
    var currentUser = new App.UserModel({id: App.Globals.userId});
    currentUser.fetch();
  }
})```
harimohanraj89 commented 10 years ago

You want your userView to have both a model and a collection. You can do that!

var user = new UserModel();
var events = new EventsCollections();

var userView = new UserView({
  model: user,
  collection: events
});

Now, inside your UserView class, you will have access to both this.model (the user) and this.collection (the events).

charlyebrown commented 10 years ago

When I add the user model to the collection, it renders the events and user objects so when the template is run, it is trying to parse through all of the data. I console.log'd this.model inside the initialize function of the UserView and was given:

child {cid: "c1", attributes: Object, _changing: false, _previousAttributes: Object, changed: Object…}_changing: false_pending: false_previousAttributes: Objectattributes: Objectevents: Array[4]0: Object1: Object2: Object3: Objectlength: 4proto: Array[0]id: "14"user: Objectbirthday: "2000-01-01"created_at: "2014-08-31T15:12:21.756Z"email: "c@c.com"id: 14months: nullname: "Charlye"role: "user"updated_at: "2014-09-02T12:47:52.781Z"years: nullproto: Objectproto: Objectchanged: Objectcid: "c1"id: "14"proto: Surrogate

The user template is:

Welcome: {{name}} Your Events: {{events}} Add Events

However, no names or events are being shown.