Search code examples
ember.jsviewcontrollers

How do I establish associations between multiple ember views and their associated objects?


I'm confused about the relationship between templates, views and models.

I understand that one of the primary roles of a view is to translate primitive events into semantic events, but I'm unclear how I should provide the necessary data to a view.

I've got a calendar_month template. The associated CalendarMonth object has an array of CalendarWeek objects, each of which has an array of CalendarDay objects. (These are not models, since they don't persist -- they're objects, generated in the CalendarMonthRoute).

So my template looks like this:

<table>
  {{#each week in weeks}}
    <tr>
      {{#each day in week.days}}
        <td>
          {{#view App.CalendarDayView}}
            {{ day.monthDay }}
          {{/view}}
        </td>
      {{/each}}
    </tr>
  {{/each}}
</table>

I'd like each of the CalendarDayView to respond to clicks, but I don't know how to get access to the specific calendar day object, which should be associated with each corresponding CalendarDayView.

App.CalendarDayView = Ember.View.extend({
  click: function(evt) {
    // do something here... but how do I know which day was clicked?
  }
});

I assume it's likely I'm not setting this up properly. Should each CalendarDay view have it's own associated instance of a CalendarDayController, providing proxy access to the corresponding CalendarDay object? If so, wouldn't that then require multiple instances of the CalendarDayController? (My understanding is that the controllers are singletons -- only one of each type should exist.)

Any advice much appreciated.


Solution

  • This can be easily achieved by using an action helper, with which you can easily pass context objects to handler methods:

    <table>
      {{#each week in weeks}}
        <tr>
          {{#each day in week.days}}
            <td>
              {{#view App.CalendarDayView}}
                <a {{action yourAction day target="view"> {{ day.monthDay }} </a>
              {{/view}}
            </td>
          {{/each}}
        </tr>
      {{/each}}
    </table>
    

    And the corresponding View:

    Vollipop.CalendarDayView = Ember.View.extend({
      yourAction : function(day){
        // perform your work on the day
      }
    });