问题描述
当我使用骨干 model.destroy()
,它似乎自动删除从DOM这一观点。
有没有办法对我来说,使用的destroy()
来发送删除请求,而是从DOM中删除自己的看法?
是这样的:
this.model.destroy({\r
等待:真实,\r
成功:函数(){\r
$('#myElement')。动画({\r
高度:0,\r
1000,\r
函数(){$('#myElement')。remove()方法}\r
});\r
}\r
});
\r
您需要重写 _onCollectionRemove()
在任何Collection视图包含该项目的意见(的)。这是当你的模型是从集合中删除这就是所谓的功能,它也是什么摧毁你的看法。特别是你如何选择覆盖它是你的,但也可能是最容易与您的动画功能来覆盖它,也许大意如下...
_onCollectionRemove:函数(模型){
VAR视图= this.children.findByModel(模型);
VAR认为这=;
视图。$('#myElement')。动画({
高度:0,
1000,
功能(){
that.removeChildView(视图);
that.checkEmpty();
}
});
}
如果您preFER手工处理去除鉴于你的摧毁
回调,只是重写 _onCollectionRemove()
包含一个空函数,做任何你想在你的删除请求的回调喜欢。我建议我以上描述,而不是在你的做这件事的办法摧毁
的回调,虽然。完全消除了函数,然后在其他地方处理在code那么它的职责与木偶的预期事件流干扰。简单地重写功能具有不同的UI效果preserves的自然流动。
修改:另一个用户的previous答案(现在由于downvoting删除)建议,也许是明智的摧毁
摧毁方法(例如,如果远程服务器宕机),它出现在用户就好像模型已被删除(在UI效果已经完成),即使服务器是无法访问的,模型依然存在。
When I use Backbone's model.destroy()
, it seems to automatically remove that view from the DOM.
Is there a way for me to use destroy()
to send the DELETE request, but remove the view from the DOM myself?
Something like:
this.model.destroy({
wait: true,
success: function(){
$('#myElement').animate({
"height" : "0",
1000,
function(){$('#myElement').remove()}
});
}
});
You need to override _onCollectionRemove()
in whichever Collection view contains the item views (documentation). This is the function which is called when your model is removed from the collection, and it's also what's destroying your view. Specifically how you choose to override it is up to you, but it might be easiest to override it with your animation function, maybe along the following lines...
_onCollectionRemove: function(model) {
var view = this.children.findByModel(model);
var that = this;
view.$('#myElement').animate({
"height" : "0",
1000,
function(){
that.removeChildView(view);
that.checkEmpty();
}
});
}
If you prefer to handle the removal of the view manually in your destroy
callback, just override _onCollectionRemove()
to contain an empty function and do whatever you'd like in the callback of your delete request. I'd recommend the approach I describe above rather than doing it in your destroy
callback, though. Completely eliminating the function and then handling it's responsibilities elsewhere in your code interferes with Marionette's intended event flow. Simply overriding the function with a different UI effect preserves the natural flow.
EDIT: Another user's previous answer (now deleted due to downvoting) suggested that it might be wise to call destroy
after the UI effect was completed. This is not a good approach for the reason OP pointed out - if something goes wrong with the destroy
method, (for example, if the remote server goes down) it appears to the user as if the model was deleted (the UI effect had already completed) even though the server was unreachable and the model remains.
这篇关于Backbone.js的`model.destroy()`自定义转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!