Backbone.js`model.destroy()`自定义转换?

时间:2015-04-24 23:59:33

标签: javascript jquery backbone.js marionette

当我使用Backbone' model.destroy()时,它似乎会自动从DOM中删除该视图。

我有没有办法使用destroy()发送DELETE请求,但是自己从DOM中删除视图?

类似的东西:



this.model.destroy({
    wait: true,
    success: function(){
        $('#myElement').animate({
            "height" : "0",
            1000,
            function(){$('#myElement').remove()}
        });
    }
});




4 个答案:

答案 0 :(得分:2)

您需要在包含项目视图(documentation)的集合视图中覆盖_onCollectionRemove()。这是从模型中删除模型时调用的函数,它也是破坏视图的内容。具体来说,你如何选择覆盖它取决于你,但用动画功能覆盖它可能是最简单的,也许是沿着以下几行......

_onCollectionRemove: function(model) {
  var view = this.children.findByModel(model);
  var that = this;
  view.$('#myElement').animate({
        "height" : "0",
        1000,
        function(){
            that.removeChildView(view);
            that.checkEmpty();
        }
    });
}

如果您希望在destroy回调中手动删除视图,只需覆盖_onCollectionRemove()以包含空函数,并在删除回调中执行任何操作请求。我建议使用上面描述的方法,而不是在destroy回调中进行此操作。完全消除该功能,然后在代码中的其他地方处理它的职责会干扰Marionette的预期事件流程。简单地用不同的UI效果覆盖函数可以保留自然流程。

编辑:其他用户之前的回答(现在由于downvoting而被删除)表明在UI效果完成后调用destroy可能是明智之举。对于OP指出的原因,这不是一个好方法 - 如果destroy方法出现问题(例如,如果远程服务器出现故障),则用户看起来好像模型已被删除( UI效果已经完成)即使服务器无法访问且模型仍然存在。

答案 1 :(得分:2)

提到的onBeforeDestroy方法对我不起作用。它在骨干中引发错误(删除删除方法) 我的解决方案具有相同的方法,并且在itemView

中运行良好
var chair1 = new Chair("red")
var chair2 = new Chair("green")

Promise.resolve("cherry")
    .bind(chair1)            // Changing the binding to `chair1`
    .then(chair1.build)
    .tap(console.log)
    .bind(chair2)            // Changing the binding to `chair2`
    .then(chair2.build)
    .tap(console.log);

答案 2 :(得分:1)

您需要使用以下其中一项:

  • collection.remove model
  • collection.reset collection.model

每个方法都会重新渲染您的集合或复合视图。

使用js或jQuery直接从集合/复合视图中删除元素并不是一种好习惯;

答案 3 :(得分:1)

我们可以专注于视图生命周期,而不是专注于模型事件。为此,Marionette在Marionette.View上提供onBeforeDestroy: function () { $('#myElement').animate({ "height" : "0", 1000 }); } 回调(由所有Marionette视图扩展)。在ItemView中,您可以像这样定义回调

$.animate

他们在这里是一个重要的警告。由于$.animate是异步函数,因此可能在onBeforeDestroy完成转换之前删除视图。因此,我们必须对onBeforeDestroy: function () { var animationDelay = 1000ms; this.remove = _.delay(_.bind(this.remove, this), animationDelay ); this.$el.animate({ "height" : "0", animationDelay }); } 进行修改。

View.remove()

基本上,我们在这里做的是设置动画运行后要触发的this.remove方法,确保在调用SQLSTATE[42S02]: Base table or view not found: 1146 Table 'sistemal5.cotizacions' doesn't exist (SQL: insert into `cotizacions` (`customer_id`, `total`, `updated_at`, `created_at`) values (1501, 150.69, 2015-05-11 03:16:25, 2015-05-11 03:16:25)) 时,在动画之后异步调用它。跑过,匆匆处理。我想,你也可以用Promises做到这一点,但这需要更多的开销。