Emberjs 1.0.0-RC3: using NEEDS-API to access other

2019-09-02 20:32发布

I want to render events and appointments on thesame page. But when I use the needs api from the AppointmentController to have access to EventsController, I can see that it returns appointments inside the 'events controller content property' when inspected. But when i try to use that returned content that contains 'appointments' to fetch out the appointments it fails. I am fetching events content in AppintmentsController with eventAppt = this.get('controllers.events').get('model'); which fetches the content and this returned content has 'appointments' as part of its data, but when I try to get the list of appointments inside the returned content's data using: eventAppt.get('appointments'); this.set('content', myAppoint);, it always fails with Cannot call method 'indexOf' of undefined.

The jsfiddle

   App.AppointmentsController = Em.ArrayController.extend({
     needs: ['events'],

     appoint: function(){
       console.log("this: ", this.toString());

       var eventAppt = this.get('controllers.events').get('model');

        //This returns the correct data that includes 'appointments'
       console.log(eventAppt);

       var myAppoint=  eventAppt.get('appointments');

       this.set('content', myAppoint);

       //This fails with 'Cannot call method 'indexOf' of undefined'
       console.log(this.get(myAppoint));
     }
  });

The EventController

 App.EventsController = Em.ArrayController.extend({

});

The model:

App.Event = DS.Model.extend({
  title: DS.attr('string'),
  start: DS.attr('date'),
  allDay: DS.attr('boolean'),
  appointments: DS.hasMany('App.Appointment')
});

Does any one have an idea why this is not working.

1条回答
放荡不羁爱自由
2楼-- · 2019-09-02 20:47

After looking better at your code it's obvious why you are getting the error. Let me try to explain. When you do:

var eventAppt = this.get('controllers.events').get('model');

this returns an array of eventsand inside this array's elements is where your appointments are. Therefore doing:

//does not work because eventAppt is an array
var myAppoint=  eventAppt.get('appointments');

throws correctly an error because you are tying to get appointments from an array of events, makes sense?

So, if you need all the appointments living inside your event models then you should loop over your events content and extract the appointments, or rather something like this if you only want one specific appointment:

var eventAppt = this.get('controllers.events').get('model');
eventAppt.objectAt(1).get('appointments') // this prints correctly the appointments of the first event in the array of events.

I hope this makes things more clear now.

查看更多
登录 后发表回答