将事件委派给Backbone中的父视图 [英] Delegating events to a parent view in Backbone

查看:242
本文介绍了将事件委派给Backbone中的父视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的观点, TuneBook ,有几个子视图类型为 ClosedTune 。我也为每个乐曲 OpenTune 分别提供了全页视图。相同的事件绑定在 ClosedTune OpenTune 中,所以我设计了我的应用程序,以便他们都继承自共享'抽象'视图调整

My view, TuneBook, has several child views of type ClosedTune. I also have separate full page views for each tune, OpenTune. The same events are bound within ClosedTune and OpenTune, so I've designed my app so that they both inherit from a shared 'abstract' view Tune.

为了使我的应用程序更可扩展,我希望每个 ClosedTune 被委派给 TuneBook ,但为了可维护性,我想要同样的处理程序(存储在$ code >调用)由 TuneBook 使用(虽然他们显然需要包装在一些功能中)。

To make my app more scaleable I would like the events for each ClosedTune to be delegated to TuneBook, but for maintainability I would like the same handlers (the ones stored in Tune) to be used by TuneBook (although they'd obviously need to be wrapped in some function).

我的问题是,在 TuneBook 之内,找到正确的 ClosedTune 来调用处理程序。什么是建立这个的好方法,还是将事件委托给父级视图有其他好的解决方案?

The problem I have is, within TuneBook, finding the correct ClosedTune to call the handler on. What's a good way to architect this, or are there other good solutions for delegating events to a parent view?

注意 - 不是骨干视图:从父级继承和扩展事件(这是关于从父类继承的孩子,而我要询问DOM中的父节点的子节点)

Note - not a duplicate of Backbone View: Inherit and extend events from parent (which is about children inheriting from a parent class, whereas I'm asking about children which are child nodes of the parent in the DOM)

推荐答案

在您的父视图(也从 Backbone.Events 扩展)中,我将绑定 onEvent 到DOM事件。在触发时,它会触发一个骨干事件,包括你的孩子看到的一些id属性(可能是一些行id?)。

In your parent view (extending also from Backbone.Events), I would bind onEvent to the DOM event. On trigger, it would fire a backbone event including some "id" attribute that your child views know (presumably some row id?).

var TuneBook = Backbone.View.extend(_.extend({}, Backbone.Events, {
    events: {
        "click .tune .button": "clickHandler"
    },
    clickHandler: function (ev) {
        this.trigger('buttonClick:' + ev.some_id_attr, ev);
    },

}));

然后,子视图将自然地订阅与之相关的父视图事件。下面我在初始化中传递父视图以及在选项之前使用的特殊id属性。

Child views would then naturally subscribe to the parent views event that concerns them. Below I do it in initialize passing the parent view as well as that special id attribute you used before in options.

var ClosedTune = Backbone.View.extend({

    initialize: function (options) {
        options.parent.on('buttonClick:' + options.id, this.handler, this);
    },

    handler: function (ev) {
        ...
    },

});

您当然也可以在 Tune OpenTune

这篇关于将事件委派给Backbone中的父视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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