火灾事件写在孩子鉴于Backbone.js的 [英] fire event written in child view in backbone.js

查看:212
本文介绍了火灾事件写在孩子鉴于Backbone.js的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的骨干JS。
假设我有所谓的childView子视图,并呼吁parentView父视图。

I am using backbone js. suppose i have a child view called 'childView' and a parent view called 'parentView'.

parentView = Backbone.View.extend({
  render: function () {
    new childView().render();
  }
})

childView = Backbone.View.extend({
  render: function () {

  },
  events: {
    'click .abc' : 'fireEvent'
  }
})

我需要调用点击一个parentView写在childView事件。

I need to call click event written in childView in a parentView.

推荐答案

最简单的方法是使用 Backbone.View 的实例。 Backbone.View Backbone.Events 混合,给你可能使用它作为事件聚合器。

The simplest way is to use Backbone.View's instance. Backbone.View is mixed with Backbone.Events which give you possibility to use it as event aggregator.

举例您的情况:

childView = Backbone.View.extend({
  render: function () {

  },
  events: {
    'click .abc' : 'fireEvent'
  }, 
  fireEvent: function (e) {
      this.trigger('child:event:fired', e);
  }
});

和在父视图:

parentView = Backbone.View.extend({
  render: function () {
    this.childView = new childView();
    this.childView.on('child:event:fired', this.onChildEvent, this);
    childView .render();
  }, 
  onChildEvent: function (e) {
        console.log("child view event");
  },
  closeThisView: function () {
    this.childView.off('child:event:fired', this.onChildEvent, this);
  }
})

此方式,您可以订阅childView事件,但你需要从所有预订手动管理解除绑定。

This way you can subscribe to childView events, but you need to manually manage unbinding from all subscriptions.

对于同一问题的另一个解决方案可以通过声明的全球盛会汇集了两种观点中找到。

Another solution for the same issue can be found by declaring global event aggregator for both views.

var vent = _.extend({}, Backbone.Events);

而在你的看法正好与触发 vent.trigger 需要事件和订阅/与退订发泄。(开/关)方法。

And in your views just trigger needed events with vent.trigger and subscribe/unsubscribe with vent.(on/off) methods.

这篇关于火灾事件写在孩子鉴于Backbone.js的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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