在控制器中订阅一个 DS.Model 事件
Subscribe to a DS.Model event in controller
我有以下控制器:
export default Controller.extend({
/* model is an array of Posts */
didDeletePost(post) {
/* PROBLEM HERE : post is an InternalModel */
this.get('model').removeObject(post);
/* do other stuff with post */
},
actions: {
markPostForDelete(post) {
post.markForDelete(); /* starts a timer */
post.one('didDelete', this, this.didDeletePost);
},
clearMarkPostForDelete(post) {
post.clearMarkForDelete(); /* cancel a timer which will destroyRecord */
post.off('didDelete', this, this.didDeletePost);
}
}
});
但是从 didDeletePost
中的 model
中删除 post
不起作用,因为 post
参数是 InternalModel
,而不是 DS.Model
.
我怎样才能做到这一点?
这样做起来似乎并不容易,我想应该有更好的方法来实现这种定时器?
实际上您不需要从 model
中删除 post。
请查看我提供的技巧:https://ember-twiddle.com/25de9c8d217eafe03aea874f8eefb0fd
根据我的经验和其他人告诉我的情况,监听事件而不是调用 actions/functions 会使您陷入非常混乱的事件链(至少对我而言,这似乎证明了这一点)。
我会用一个标志稍微手动一点(为了简单起见,这里是模型中的所有示例,但您可能需要根据其他交互移动到控制器):
export default DS.Model.extend({
markPostForDelete() {
this.set('marked', true).then( () => /*function in model to start timer and then call this.deleteMarked() */);
},
clearMarkPostForDelete() {
this.set('marked', false)
},
deleteMarked() {
if(this.get('marked')) {
this.destroyRecord();
}
}
}); /* end of model */
我有以下控制器:
export default Controller.extend({
/* model is an array of Posts */
didDeletePost(post) {
/* PROBLEM HERE : post is an InternalModel */
this.get('model').removeObject(post);
/* do other stuff with post */
},
actions: {
markPostForDelete(post) {
post.markForDelete(); /* starts a timer */
post.one('didDelete', this, this.didDeletePost);
},
clearMarkPostForDelete(post) {
post.clearMarkForDelete(); /* cancel a timer which will destroyRecord */
post.off('didDelete', this, this.didDeletePost);
}
}
});
但是从 didDeletePost
中的 model
中删除 post
不起作用,因为 post
参数是 InternalModel
,而不是 DS.Model
.
我怎样才能做到这一点?
这样做起来似乎并不容易,我想应该有更好的方法来实现这种定时器?
实际上您不需要从 model
中删除 post。
请查看我提供的技巧:https://ember-twiddle.com/25de9c8d217eafe03aea874f8eefb0fd
根据我的经验和其他人告诉我的情况,监听事件而不是调用 actions/functions 会使您陷入非常混乱的事件链(至少对我而言,这似乎证明了这一点)。
我会用一个标志稍微手动一点(为了简单起见,这里是模型中的所有示例,但您可能需要根据其他交互移动到控制器):
export default DS.Model.extend({
markPostForDelete() {
this.set('marked', true).then( () => /*function in model to start timer and then call this.deleteMarked() */);
},
clearMarkPostForDelete() {
this.set('marked', false)
},
deleteMarked() {
if(this.get('marked')) {
this.destroyRecord();
}
}
}); /* end of model */