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

发布于 2025-01-03 10:15:58 字数 267 浏览 0 评论 0原文

backbone.js 文档 中,它说:

制作一个方便的事件调度程序可以协调应用程序不同区域之间的事件: vardispatcher = _.clone(Backbone.Events)

任何人都可以解释如何实现调度程序以从一个视图到另一个视图进行通信吗?我必须将代码放在应用程序中的什么位置?

In backbone.js documentation it says:

To make a handy event dispatcher that can coordinate events among different areas of your application: var dispatcher = _.clone(Backbone.Events)

Can anyone explain how to implement the dispatcher to communicate from one view to another? Where do I have to place the code in my app?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

亚希 2025-01-10 10:15:58

这是一篇关于使用 事件聚合器

谁能解释一下如何实现调度程序从一个视图到另一个视图的通信?我必须将代码放置在应用程序中的什么位置?

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

从我的角度来看,我认为这篇文章很好地解释了这一点。

Here is a good article about using an event aggregator.

Can anyone explain how to implement the dispatcher to communicate from one view to another? Where do I have to place the code in my app?

You will probably have some kind of App Controller object, which will control the flow of the app, creating views, models, etc. This is also a good place for the event aggregator.

From my point of view, I think that article explains it pretty well.

瑾夏年华 2025-01-10 10:15:58

最近,我需要一个 EventDispatcher 来处理大量事件,而又不会丢失它们的名称和行为。

也许它对你也有帮助。

这是一个简单的示例视图:

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。事件本身是在模板对象中预定义的。您的 IDE 应该能够识别它们并引导您完成列表。

如您所见,调度程序自行运行。只有您的视图或其他任何东西需要来自 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 事件系统的行为不会受到任何影响,可以正常使用。

Recently I needed an EventDispatcher to handle a large amount of events without loosing track of their names and their behave.

Perhaps it helps you too.

Here a simple example 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){

            }

        })
    ))();
});

Here the EventDispatcher with some example events. The events itself are predefined in the template Object. Your IDE should recognize them and lead you through the list.

As you can see, the Dispatcher run on its own. Only your View or whatever needs underlying Event methods from 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;
    }

});

The behavior of Backbones Event-system is not affected in any way and can be used as normal.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文