Emberjs1.0.0-RC3: undefined when calling and stori

2019-08-28 17:01发布

问题:

In this jsfiddle, inside the didInsertElement hook, I am trying to call a controller method called eventJSON, which is defined in CalendarsController, I am storing or passing that call to the controller action in a variable called calendarJSON that i declared inside the didInsertElement hook in the CalendarsView. But when I log the result, it gives undefined. Also if I put a debugger inside the didInsertElement hook and inspect the variable in the console, it returns undefined.

I want to store the data returned from var calendarJSON = this.get('controller').send('eventJSON'); in variable because I want to subsequently passed that data to fullcalendar jquery.

The jsfiddle

The controller:

 App.CalendarsController = Em.ArrayController.extend({
    eventJSON: function() {
     //returns the json of controller's content
      this.invoke('toJSON');
      return this.get('content');
    }
 });

The view:

 App.CalendarsView = Ember.View.extend({
   templateName: 'calendars',
   attributeBindings: ['id'],
   id: "mycalendar",

   didInsertElement: function() {
    debugger;
    this._super();

    //Right here is the problem
    var calendarJSON = this.get('controller').send('eventJSON');
    console.log(calendarJSON);

    this.$().fullCalendar({
       header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,agendaWeek,agendaDay'
        },
        editable: true,

        events: calendarJSON 
    });   
  }
});

回答1:

I modified to what is pasted below to get it to run. Basically, I wasn't using the keyword return to return anything from the controller. Secondly, I broke the steps to accessing the controller action into 2 steps. In step 1, I fetch the controller and then I call the event on it as shown below:

 var controller = this.get('controller');
 var calendarJSON = controller.eventJSON();

The working jsfiddle.

The adjusted code:

App.CalendarsController = Em.ArrayController.extend({
  eventJSON: function() {
    m = this.get('content');
    m.invoke('toJSON');
    console.log(m);
    return m;
 }
}); 

The view:

App.CalendarsView = Ember.View.extend({
 templateName: 'calendars',
 attributeBindings: ['id'],
 id: "mycalendar",

 didInsertElement: function() {
    this._super();

   var controller = this.get('controller');
   var calendarJSON = controller.eventJSON();

   console.log(calendarJSON);

   this.$().fullCalendar({
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,agendaWeek,agendaDay'
        },

        editable: true,
        events: calendarJSON 
    });  
   }
});