在backbone.js 中从另一个视图访问一个视图中的函数 [英] access function in one view from another in backbone.js

查看:20
本文介绍了在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 函数.据我了解,我需要以某种方式绑定它们.是否可以在初始化函数中绑定它们?

So I would like to runf function in one view form another. As far as I understand, I need to bind them somehow. Is it possible to bind them in initialize function?

我在这里看到的例子:Backbone.js - 从一个视图绑定到另一个? .他们创建两个对象,然后以某种方式绑定它们.

I saw here example: Backbone.js - Binding from one view to another? . They creating both objects and than somehow binding them.

提前致谢,

推荐答案

我有点喜欢使用事件聚合器"模式.我确保每个视图都获得了相同事件聚合器对象的副本,并且它们都可以通过它相互交谈......有点像 CB 收音机 :)

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")
    }
});

这篇关于在backbone.js 中从另一个视图访问一个视图中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆