Ember Data 1.0 - 如何在数据加载时触发模型上的观察器

Ember Data 1.0 - How to trigger observer on model when data loads?

本文关键字:模型 观察 加载 数据 Data Ember      更新时间:2023-09-26

我正在构建的Ember应用程序使用Leaflet.js作为其大地图。我有一个模型的观察者,该模型将向量添加到地图并保持更新:

Qp.Region = DS.Model.extend({
  // Attributes
  name: DS.attr('string'),
  maxLat: DS.attr('number'),
  minLat: DS.attr('number'),
  minLon: DS.attr('number'),
  maxLon: DS.attr('number'),
  // Helper properties
  _vector: null,
  // Computed properties
  leafletBounds: function() {
    var properties = ['minLat', 'maxLat', 'minLon', 'maxLon'],
        bounds = [];
    for ( var i = 0; i < 2; i++ ) {
      var lat = Number(this.get(properties[i])),
          lng = Number(this.get(properties[i + 2]));
      if ( lat !== lat || lng !== lng )
        return;
      bounds.pushObject(L.latLng({
        lat: lat,
        lng: lng
      }));
    }
    return bounds;
  }.property('minLat', 'maxLat', 'minLon', 'maxLon'),
  boundsDidChange: function() {
    var existingVector = this.get('_vector'),
        vector = existingVector || Ember.Object.create({
          _layer: null,
          model: this
        }),
        bounds = this.get('leafletBounds');
    if ( !bounds )
      return;
    vector.set('bounds', bounds);
    if ( !existingVector ) {
      Qp.L.regions.pushObject(vector);
      this.set('_vector', vector);
    }
  }.observes('leafletBounds'),
  shouldRemoveSelf: function() {
    if ( !this.get('isDeleted') && !this.get('isDestroying') )
      return;
    var existingVector = this.get('_vector');
    if ( existingVector ) {
      Qp.L.regions.removeObject(existingVector);
      this.set('_vector', null);
    }
  }.observes('isDeleted', 'isDestroying')
})

:注:这在 Ember Data 修订版 0.13 中完美配合

现在我正在更新到 Ember Data 1.0 beta 2,并且矢量不再添加到地图中。如果我在初始化时保存对模型的引用...

init: function() {
  this._super.apply(this, arguments);
  window.test = this;
}

。,然后从 Chrome 开发者工具控制台调用window.test.boundsDidChange(),此时将显示我的灯具中最后一个区域的矢量。因此,我知道一切仍在工作,除了在模型数据加载时不再调用观察器。

如何让boundsDidChange观察器在模型加载或更新时触发?

这可能是由于 rc8 的变化。 查找标题为"未使用的计算属性不触发观察器"的部分: http://emberjs.com/blog/2013/08/29/ember-1-0-rc8.html

更改是计算属性在被某些东西实际检索之前永远不会计算,这意味着如果它们不直接显示,则它们的观察者将无法可靠地工作。

可以在对象 init 中get leafletBounds 属性,也可以让 boundsDidChange 函数观察计算属性的所有组件。

boundsDidChange: function() { 方法主体中没有任何更改
}.observes('minLat', 'maxLat', 'minLon', 'maxLon')