javascript 如何销毁这个 Backbone.js View 实例?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8379240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:16:02  来源:igfitidea点击:

How do I destroy this Backbone.js View instance?

javascriptjqueryoopbackbone.js

提问by TIMEX

var CheckboxView = Backbone.View.extend({
        tagName:'div',
        template: _.template(item_temp,{}),
        events:{
            'click .checkoff_friend':'toggleCheckFriend',
        },
        initialize: function(){
        },
        render:function(){

        },
        toggleCheckFriend:function(){
            //destroy this View instance. 
        }
    });

var cv = new CheckboxView();

How do I destroy the instance? When toggle is activated, I want the instance of that view to dissapear forever.

如何销毁实例?当切换被激活时,我希望该视图的实例永远消失。

回答by sdailey

My answer for a similar question was received well, and has worked well for me. Here's a look at my destroy_view function

我对类似问题的回答很受欢迎,对我来说效果很好。下面来看看我的 destroy_view 函数

(orig. question https://stackoverflow.com/a/11534056/986832) Response:

(原问题https://stackoverflow.com/a/11534056/986832)响应:

I had to be absolutely sure the view was not just removed from DOM but also completely unbound from events.

我必须绝对确定该视图不仅从 DOM 中删除,而且还完全不受事件的约束。

destroy_view: function() {

    //COMPLETELY UNBIND THE VIEW
    this.undelegateEvents();

    $(this.el).removeData().unbind(); 

    //Remove view from DOM
    this.remove();  
    Backbone.View.prototype.remove.call(this);

    }

Seemed like overkill to me, but other approaches did not completely do the trick.

对我来说似乎有点矫枉过正,但其他方法并没有完全做到这一点。

回答by Esailija

Do not assign the instance to any variable (I don't see any need to since Views in backbone are driven by events), and in your toggleCheckFriendmethod remove all data and events, which makes the instance available for garbage collection.

不要将实例分配给任何变量(我认为没有任何必要,因为主干中的视图是由事件驱动的),并且在您的toggleCheckFriend方法中删除所有数据和事件,这使得该实例可用于垃圾收集。

    toggleCheckFriend:function(){
    $(this.el).removeData().unbind();

    }

回答by rkw

Does that View have a model behind it?

该视图背后是否有模型?

If you want the model removed (from the db), you can use: this.model.destroy()

如果您想删除模型(从数据库中),您可以使用: this.model.destroy()

After that, you can remove just the View itself from the DOM by calling this.remove(). Documentation mentions that it is the equivalent of $(this.el).remove().

之后,您可以通过调用从 DOM 中删除视图本身this.remove()。文档提到它相当于$(this.el).remove().

Note that the 'this' above refers to the View itself, so you would have to _.bindAll(this, 'toggleCheckFriend')

请注意,上面的“this”指的是视图本身,因此您必须 _.bindAll(this, 'toggleCheckFriend')