Ember, working with a model

落爺英雄遲暮 提交于 2019-12-12 10:18:29

问题


I'm confused about how to set up retrieve information from my (dynamic) model in Ember.js

Here is my model (works so far):

App.Router.map(function() {
        this.resource('calendar', { path: '/calendar/:currentMonth'});
});

App.CalendarRoute = Ember.Route.extend({
  model: function (params) {
    var obj = {
       daysList: calendar.getDaysInMonth("2013", params.currentMonth),
       currentMonth: params.currentMonth
    };
    return obj;
  }
});

I just want to get back the 'currentMonth' attribute:

App.CalendarController = Ember.Controller.extend({
  next: function() {
    console.log(this.get('currentMonth'));
  }
});

But I am getting an "undefined" error.

Do I have to explicitly declare my model (Ember.model.extend()) in order to get and set values?


回答1:


There are some conventions that you might not be aware of in regards to setting a Model into a Controller.

In a Route, model can be any object or collection of objects you define. There is a huge deal of conventions that apply and for most cases, you don't have to specify anything as it uses the names of various objects to guide itself on building the query and a set the content of your controller, however, in your particular code, you are return obj as the model.

Ember provides a hook called setupController that will set this object into your controller's content property. Example:

App.CalendarRoute = Ember.Route.extend({
  model: function (params) {
    var obj = {
       daysList: calendar.getDaysInMonth("2013", params.currentMonth),
       currentMonth: params.currentMonth
    };
    return obj;
  },
  setupController: function(controller, model) {
     // model in this case, should be the instance of your "obj" from "model" above
     controller.set('content', model);
  }
});

With that said, you should try console.log(this.get('content.currentMonth'));



来源:https://stackoverflow.com/questions/15886841/ember-working-with-a-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!