我正在构建的 Ember 应用程序将 Leaflet.js 用于其大 map 。我在一个模型上有一个观察者,它向 map 添加一个矢量并保持更新:
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')
})
N.B. 这与 Ember Data rev. 完美配合。 0.13。
现在我正在更新到 Ember Data 1.0 beta 2,矢量不再添加到 map 中。如果我在初始化时保存对模型的引用...
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
变化是计算属性在被某些东西实际检索之前永远不会被计算,这意味着如果它们没有被直接显示,它们的观察者就不能可靠地工作。
您可以在您的对象初始化中获取
leafletBounds
属性,或者您可以让您的boundsDidChange
函数观察计算属性。
boundsDidChange: 函数() {
//方法体中没有任何变化
}.observes('minLat', 'maxLat', 'minLon', 'maxLon')
关于javascript - Ember Data 1.0 - 如何在数据加载时触发模型上的观察者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18752669/