问题
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:
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 events
and 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.
来源:https://stackoverflow.com/questions/16771000/emberjs-1-0-0-rc3-using-needs-api-to-access-other-controller-content-property