Destroy or remove a view in Backbone.js

后端 未结 7 1647
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 09:57

I\'m currently trying to implement a destroy/remove method for views but I can\'t get a generic solution to work for all my views.

I was hoping there would be an eve

相关标签:
7条回答
  • 2020-11-27 10:38

    I think this should work

    destroyView : function () {
        this.$el.remove();
    }
    
    0 讨论(0)
  • 2020-11-27 10:43

    According to current Backbone documentation....

    view.remove()

    Removes a view and its el from the DOM, and calls stopListening to remove any bound events that the view has listenTo'd.

    0 讨论(0)
  • 2020-11-27 10:45

    I know I am late to the party, but hopefully this will be useful for someone else. If you are using backbone v0.9.9+, you could use, listenTo and stopListening

    initialize: function () {
        this.listenTo(this.model, 'change', this.render);
        this.listenTo(this.model, 'destroy', this.remove);
    }
    

    stopListening is called automatically by remove. You can read more here and here

    0 讨论(0)
  • 2020-11-27 10:45

    This is what I've been using. Haven't seen any issues.

    destroy: function(){
      this.remove();
      this.unbind();
    }
    
    0 讨论(0)
  • 2020-11-27 10:50

    You could use the way to solve the problem!

    initialize:function(){
        this.trigger('remove-compnents-cart');
        var _this = this;
        Backbone.View.prototype.on('remove-compnents-cart',function(){
            //Backbone.View.prototype.remove;
            Backbone.View.prototype.off();
            _this.undelegateEvents();
        })
    }
    

    Another way:Create a global variable,like this:_global.routerList

    initialize:function(){
        this.routerName = 'home';
        _global.routerList.push(this);
    }
    /*remove it in memory*/
    for (var i=0;i<_global.routerList.length;i++){
        Backbone.View.prototype.remove.call(_global.routerList[i]);
    }
    
    0 讨论(0)
  • 2020-11-27 10:51

    Without knowing all the information... You could bind a reset trigger to your model or controller:

    this.bind("reset", this.updateView);
    

    and when you want to reset the views, trigger a reset.

    For your callback, do something like:

    updateView: function() {
      view.remove();
      view.render();
    };
    
    0 讨论(0)
提交回复
热议问题