backbone.js - 使用事件调度程序var dispatcher = _.clone(Backbone.Events)

时间:2012-02-07 12:38:23

标签: events backbone.js dispatcher

backbone.js documentation中说:

创建一个方便的事件调度程序,可以协调应用程序不同区域之间的事件:var dispatcher = _.clone(Backbone.Events)

有人能解释如何实现调度程序从一个视图到另一个视图的通信吗?我在哪里将代码放在我的应用程序中?

2 个答案:

答案 0 :(得分:13)

这是一篇关于使用event aggregator的好文章。

  

有人能解释如何实现调度程序从一个视图到另一个视图的通信吗?我在哪里将代码放在我的应用程序中?

您可能会有某种App Controller对象,它将控制应用程序的流程,创建视图,模型等。这也是事件聚合器的好地方。

从我的观点来看,我认为那篇文章很好地解释了它。

答案 1 :(得分:0)

最近我需要一个EventDispatcher来处理大量事件,而不会忘记他们的名字和行为。

也许它对你有帮助。

这里有一个简单的示例View:

define(['backbone', 'underscore', 'eventDispatcher'], 
    function(Backbone, _, dispatcher){

        new (Backbone.View.extend(_.extend({
            el: $('#anyViewOrWhatever'),
            initialize: function () {
                window.addEventListener('resize', function () {
                    // trigger event
                    dispatcher.global.windowResize.trigger();
                });

                // create listener
                dispatcher.server.connect(this, this.doSomething);

                // listen only once
                dispatcher.server.connect.once(this, this.doSomething);

                // remove listener:
                dispatcher.server.connect.off(this, this.doSomething);
                // remove all listener dispatcher.server.connect from this:
                dispatcher.server.connect.off(null, this);
                // remove all listener dispatcher.server.connect with this method:
                dispatcher.server.connect.off(this.doSomething);
                // remove all listener dispatcher.server.connect no matter what and where:
                dispatcher.server.connect.off();

                // do the same with a whole category
                dispatcher.server.off(/* ... */);

                // listen to all server events
                dispatcher.server.all(this, this.eventWatcher);

            },
            doSomething: function(){

            },
            eventWatcher: function(eventName){

            }

        })
    ))();
});

这里的EventDispatcher包含一些示例事件。事件本身是在模板Object中预定义的。您的IDE应该识别它们并引导您完成列表。

如您所见,Dispatcher独立运行。只有你的View或其他任何需要来自Backbone的基础事件方法。

// module eventDispatcher
define(['backbone', 'underscore'], function (Backbone, _) {

    var instance;
    function getInstance () {
        if ( !instance ) {
            instance = createInstance();
        }
        return instance;
    }
    return getInstance();

    function createInstance () {
        // dummy function for your ide, will be overwritten
        function e (eventContext, callback) {}
        var eventHandler = {},

            // feel free to put the template in another module
            // or even more split them in one for each area
            template = {
                server: {
                    connect: e,
                    disconnect: e,
                    login: e,
                    logout: e
                },
                global: {
                    windowResize: e,
                    gameStart: e
                },
                someOtherArea: {
                    hideAll: e
                }
            };

        // Create Events
        _.each(template, function (events, category) {
            var handler = eventHandler[category] = _.extend({}, Backbone.Events);
            var categoryEvents = {
                // turn off listener from <category>.<**all events**> with given _this or callback or both:
                // off() complete purge of category and all its events.
                // off(callback) turn off all with given callback, no matter what this is
                // off(null, this) turn off all with given this, no matter what callback is
                // off(callback, this) turn off all with given callback and this
                off: function (callback, _this) {
                    if(!callback && _this){
                        handler.off();
                    }else{
                        _.each(template[category], function(v, k){
                            k != 'off' && template[category][k].off(callback, _this);
                        });
                    }
                }
            };
            events.all = e;
            _.each(events, function (value, event) {
                // create new Listener <event> in <category>
                // e.g.: template.global.onSomething(this, fn);
                categoryEvents[event] = function (_this, callback) {
                    _this.listenTo(handler, event, callback);
                };
                // create new Listener <event> in <category> for only one trigger
                // e.g.: template.global.onSomething(this, fn);
                categoryEvents[event].once = function (_this, callback) {
                    _this.listenToOnce(handler, event, callback);
                };
                // trigger listener
                // e.g.: template.global.onSomething.trigger();
                categoryEvents[event].trigger = function (debugData) {
                    console.log('**Event** ' + category + '.' + event, debugData ? debugData : '');
                    handler.trigger(event);
                };
                // turn off listener from <category>.<event> with given _this or callback or both:
                // off() complete purge of category.event
                // off(callback) turn off all with given callback, no matter what this is
                // off(null, this) turn off all with given this, no matter what callback is
                // off(callback, this) turn off all with given callback and this
                // e.g.: template.global.onSomething.off(fn, this);
                categoryEvents[event].off = function (callback, _this) {
                    handler.off(event, callback, _this);
                }

            });
            template[category] = categoryEvents;
        });

        return template;
    }

});

Backbones事件系统的行为不受任何影响,可以正常使用。