用于DOM操作的Ember最佳实践

时间:2014-10-23 08:17:46

标签: javascript ember.js

我在Ember写了一个网络日历,而且我需要在几天内填充我的桌子。 我有所有当前月份的数组,我有简单的js循环,但我不明白哪一个是Ember方式动态填写我的HTML。 我找到了两种方法:使用Handlebars助手或使用View。我认为视图更好但我无法将视图与模板和控制器连接起来..

这是我的普通js代码:

var html = '';
var day = 1;
for(i = 1; i <= 6; i++){ //6 rows
    html += '<tr id="days-row">';
    for(j = 1; j <= 7; j++){ //7 coloumns
        html += '<td>'; 
        if(day <= totDayInMonth && (i > 1 || j >= firstDayOfWeekNumber )){
            html += day;
            day++;
        } else {
            html += '&nbsp;';
        }
        html += '</td>';
    }
    if(day >= totDayInMonth){
        break;
    }
    html += '</tr>'; 
}  
html + '</tr>';

在这里我想出了什么(它们都不起作用)

解决方案1 ​​

//controller
WebCalendar.CalController = Ember.ArrayController.extend({
    itemController: 'days'

});

WebCalendar.DaysController = Ember.ObjectController.extend({
    getMonthDays: function(){
        var monthNumber = this.get("monthNumber");
        var daysInMonth = this.get("daysInMonth");
        var totDayInMonth = daysInMonth[monthNumber];

        var days = [];
        for( i = 1; i < totDayInMonth; i++){
            days.push(i);
        }
        return days;

    }.property('monthNumber')
});

//helper
Handlebars.registerHelper('calRow', function(items, options) {
  for(i = 1; i <= 6; i++){  
      var html = "<tr id='days-row'>";
      for(j = 1; j <= 7; j++) {
        html = html + "<td>";
        if(day <= totDayInMonth){
            html += day;
        } else {
            html += '&nbsp;'; 
        }
        html += "</td>";
      }
     html + "</tr>";
  }
});

//cal.hbs
{{calRow today}}

解决方案2 - 查看

//controllers
WebCalendar.CalController = Ember.ArrayController.extend({
    itemController: 'days'

});

WebCalendar.DaysController = Ember.ObjectController.extend({
    getMonthDays: function(){
        var monthNumber = this.get("monthNumber");
        var daysInMonth = this.get("daysInMonth");
        var totDayInMonth = daysInMonth[monthNumber];

        var days = [];
        for( i = 1; i < totDayInMonth; i++){
            days.push(i);
        }
        return days;

    }.property('monthNumber')
});

//days_view
WebCalendar.DaysView = Ember.View.extend({
  controller: WebCalendar.DaysController,
  templateName: 'cal',
  tagName: 'tbody',

  fillDays: function(){
        for(i = 1; i <= 6; i++){  
          var html = "<tr id='days-row'>";
          for(j = 1; j <= 7; j++) {
            html = html + "<td>";
            if(day <= totDayInMonth){
                html += day;
            } else {
                html += '&nbsp;'; 
            }
            html += "</td>";
          }
          html + "</tr>";
        }
        return html;
  }

});

//cal.hbs
{{view.fillDays}}//where I want my days to be display

Ember文档总是让我挣扎,所以任何提示都非常受欢迎!

0 个答案:

没有答案