Backbone.js View removing and unbinding

后端 未结 4 532
轮回少年
轮回少年 2021-02-03 15:36

when my page opens, I call the collection and populate the view:

var pagColl = new pgCollection(e.models); 
var pagView = new pgView({collection: pagColl});
         


        
4条回答
  •  半阙折子戏
    2021-02-03 15:46

    Here's one alternative I would suggest to use, by using Pub/Sub pattern.

    You can set up the events bound to the View, and choose a condition for such events.

    For example, PubSub.subscribe("EVENT NAME", EVENT ACTIONS, CONDITION); in the condition function, you can check if the view is still in the DOM.

    i.e.

    var unsubscribe = function() {
        return (this.$el.closest("body").length === 0);
    };
    PubSub.subscribe("addSomething",_.bind(this.addSomething, this), unsubscribe);
    

    Then, you can invoke pub/sub via PubSub.pub("addSomething"); in other places and not to worry about duplicating actions.

    Of course, there are trade-offs, but this way not seems to be that difficult.

提交回复
热议问题