2

我正在构建的 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 rev 完美配合。0.13 .

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

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

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

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

4

1 回答 1

1

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

变化是计算属性在被某些东西实际检索之前不会被计算,这意味着如果它们不直接显示,它们上的观察者就不能可靠地工作。

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

boundsDidChange: function() { // 方法体中没有任何变化
}.observes('minLat', 'maxLat', 'minLon', 'maxLon')

于 2013-09-12T02:33:02.940 回答