如何绑定在父视图子视图处理事件的背景下 [英] How to bind context of child view handling event in parent view

查看:174
本文介绍了如何绑定在父视图子视图处理事件的背景下的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的骨干视图的:

I have the following Backbone View's:

var ParentView = Backbone.View.extend({
     events: {
         "contextmenu .child-view" : "handleChildView"
     },

     initialize: function () {
        // create child view
        var child = new ChildView;
     },

     handleChildView: function () {
     }
});

var ChildView = Backbone.View.extend({

     initialize: function () {
        this.el.addClass('child-view');
     }
});

我需要处理handleChildView处理childView的contextmenu事件。但我需要得到指向同childView和目标DOM元素。

I need to handle childView's contextmenu event in handleChildView handler. But I need to get refference to childView and target DOM element.

我怎么能做出这样?

推荐答案

我通常会尽量避免。我认为这是一个反模式,因为我相信每个视图应该只处理它自己的事件。

I usually would try to avoid that. I think it's an anti-pattern since I believe each view should only handle it's own events.

在有需要的意见通知事件,我用的是事件总线模式。(发布/订阅)

When there's a need for notifying events between views, I use the event bus pattern.(publisher/subscriber)

看到这个答案我张贴早些时候:

see this answer I posted earlier:

<一个href=\"http://stackoverflow.com/questions/20181679/call-a-function-in-another-marionette-itemview/20182584#20182584\">Call在另一Marionette.ItemView 功能

这是类似的。

你应该在你的应用程序定义一个事件总线。
而在你ChildView,发布事件时,事情发生(如点击)

You should define an event bus in your app. And in your ChildView, publish an event when something happens (like click)

var ChildView = Backbone.View.extend({
  events: {
    'click': 'handleClick'
  },
  handleClick: function() {
    //publish event
    EventBus.trigger('childViewClicked', [anything you wanna pass]);
  }
});

和你的父视图,订阅此事件:

and in your parent view, subscribe to this event:

 var ParentView = Backbone.View.extend({
   initialize: function () {
     //subscribe events:
     EventBus.on('childViewClicked', this.handleChildView, this);
   },

   handleChildView: function ([params you wanna receive]) {
   }
 });

这篇关于如何绑定在父视图子视图处理事件的背景下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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