从App.Route中的afterModel调用Ember.set时,不会触发Ember.js classNameBindings

时间:2015-01-12 20:58:35

标签: ember.js

我想要做的是根据是否已设置cookie将所选持续时间设置为默认值。我正在App.Route的afterModel中执行此检查。

如果已设置cookie,请使用cookie值,如果未将其设置为durations数组的第一个成员。

类名绑定到持续时间按钮组件,并在选择初始值后按预期工作。

我是Ember的新手,想知道我是不是以错误的方式解决这个问题,还是错过了什么?

App.Route = Ember.Route.extend({
  model: function() {
    return Ember.RSVP.hash({
      categories: categories,
      durations: durations
    })
  },
  actions: {
    setDuration: function(duration) {
      var idx = durations.indexByPropertyValue('selected',true);
      if (idx >= 0 ) {
        Ember.set(durations[idx],'selected',false);
      }
      idx = durations.indexByPropertyValue('seconds',duration);
      if (idx >= 0 ) {
        Ember.set(durations[idx],'selected',true);
        $.cookie('duration', duration)
      }
    }
  },
  afterModel: function(posts, transition) {
    var duration = $.cookie('duration');
    if (duration) {
      var idx = durations.indexByPropertyValue('seconds', duration);
      if (idx >= 0) {
        Ember.set(durations[idx],'selected',true);
      }
    } else {
      duration = durations[0].seconds;
      Ember.set(durations[0],'selected',true);
      $.cookie('duration', duration)
    }
  }
});

App.DurationButtonComponent = Ember.Component.extend({
  classNames: ['btn btn-default'],
  classNameBindings: ['selected:active'],
  selectedBinding: "duration.selected",
  tagName: 'button',
  click:function (){
    if (this.duration.selected) return;
    this.sendAction('action', this.duration.seconds);
  }
});


var durations = [
  {
    id: '1',
    num: '15',
    unit:'sec',
    seconds: 15,
    selected: false
  },
  ...
  {
    id: '5',
    num: '5',
    unit:'min',
    seconds: 300,
    selected: false
  }
]

1 个答案:

答案 0 :(得分:0)

如果要设置/观察属性,则需要将持续时间设为ember object

App.Route = Ember.Route.extend({
  model: function() {
    return Ember.RSVP.hash({
      categories: categories,
      durations: [
        Ember.Object.create({
          id: '1',
          num: '15',
          unit:'sec',
          seconds: 15,
          selected: false
        }),
        Ember.Object.create({
          id: '5',
          num: '5',
          unit:'min',
          seconds: 300,
          selected: false
         }),
      ]

     })
  }
});