在backbone.js中从另一个视图访问函数

时间:2011-10-10 03:12:12

标签: backbone.js

我有这种观点结构:

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

window.PopupView = templateLoaderView.extend({
   initialize: function () {
       this.PopupModel = new PopupModel();
       this.event_aggregator.bind("tasks_popup:show", this.loadTaskPopup);
   },

   render: function() {
       template= _.template($('#'+this.PopupModel.templateName).html());
       $(this.el).html(template(this.PopupModel.toJSON()));
       $('#'+this.PopupModel.containerID).html(this.el);
   },

   loadTaskPopup: function() {
       this.PopupModel.loadTemplate("popupTask_templateHolder", "/js/templates/popup_task.html", "1", "container_dialog");
       this.render();
   }
});

window.TaskbarView = templateLoaderView.extend({

   initialize: function () {
       this.TaskbarModel = new TaskbarModel();
       this.PopupModel = new PopupModel();
   },

   loadTaskbarPopup: function() {
       this.event_aggregator.trigger("tasks_popup:show");
   }

});

所以我想在另一个视图中运行runf函数。据我所知,我需要以某种方式绑定它们。是否可以在初始化函数中绑定它们?

我在这里看到了例子:Backbone.js - Binding from one view to another?。他们创建两个对象,然后以某种方式绑定它们。

提前致谢,

1 个答案:

答案 0 :(得分:12)

我喜欢使用“Event Aggregator”模式。我确保为每个视图提供相同事件聚合器对象的副本,并且它们都可以通过它相互通信......有点像CB无线电:)

在创建任何视图之前执行此操作:

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

现在,您可以从任何地方发布/订阅:

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")
    }
});
相关问题