access function in one view from another in backbone.js

前端 未结 1 895
-上瘾入骨i
-上瘾入骨i 2021-01-03 09:01

I have this structure of views:

window.templateLoaderView = Backbone.View.extend({});

window.PopupView = templateLoaderView.extend({
   initialize: function         


        
相关标签:
1条回答
  • 2021-01-03 09:11

    I am kind of a fan of using the "Event Aggregator" pattern. I make sure that every view is given a copy of the same event aggregator object and they can all talk to each other through it... kind of like a CB radio :)

    Do this before you create any views:

    Backbone.View.prototype.event_aggregator = _.extend({}, Backbone.Events);
    

    Now, you can publish/subscribe from anywhere:

    window.PopupView = Backbone.View.extend({
        initialize: function() {
            _.bindAll(this, "loadTaskPopup");
            this.model = new PopupModel();
            this.event_aggregator.bind("tasks_popup:show", this.loadTaskPopup);
        },
    
        loadTaskPopup: function() {
            // do something with this.model
        }
    });
    
    window.TaskbarView = Backbone.View.extend({
        loadTaskbarPopup: function() {
          this.event_aggregator.trigger("tasks_popup:show")
        }
    });
    
    0 讨论(0)
提交回复
热议问题