木偶事件之间的区别

Die*_*uin 13 events marionette

我读了marionette.js文档,我不明白之间的差别vent,reqrescommands.

我唯一明白的是命令不应该返回任何东西.

任何人都可以解释一下吗?

joe*_*ews 19

让我们从顶部开始:Backbone.wreqr是Marionette附带的Backbone插件.它为松散耦合的应用程序提供了三种消息传递模式.

这个答案包括来自Backbone.wreqr文档的示例代码- 归功于原始作者.

活动

EventAggregator对象的工作方式Backbone.Events- 它们启用了命名空间事件处理.vent只是EventAggregator对象的常见变量名称:

var vent = new Backbone.Wreqr.EventAggregator();

vent.on("foo", function(){
  console.log("foo event");
});

vent.trigger("foo");
Run Code Online (Sandbox Code Playgroud)

命令

命令与Events非常相似.区别在于语义 - 事件通知应用程序的其他部分发生了某些事情.命令指示应用程序的另一部分执行某些操作.

var commands = new Backbone.Wreqr.Commands();

commands.setHandler("foo", function(){
  console.log("the foo command was executed");
});

commands.execute("foo");
Run Code Online (Sandbox Code Playgroud)

请求/响应

RequestResponse通常由被调用的变量引用的对象reqres为应用程序组件提供了一种松散耦合的方式来请求访问对象:

var reqres = new Backbone.Wreqr.RequestResponse();

reqres.setHandler("foo", function(){
  return "foo requested. this is the response";
});

var result = reqres.request("foo");
console.log(result);
Run Code Online (Sandbox Code Playgroud)

广播和频道

为方便起见,Wreqr提供了一个radio混合三种消息传递模式的对象.命令,事件和请求可以分组为逻辑通道以防止干扰 - 例如,您可能需要不同的save命令userdocument通道.

在木偶

Marionette.Application创建的实例Commands,RequestResponse以及EventAggregator一个通道内("global" by default)使用传统的变量名.如果您需要自定义行为可以重写vent,commandsreqres变量.

_initChannel: function() {
      this.channelName = _.result(this, 'channelName') || 'global';
      this.channel = _.result(this, 'channel') || Backbone.Wreqr.radio.channel(this.channelName);
      this.vent = _.result(this, 'vent') || this.channel.vent;
      this.commands = _.result(this, 'commands') || this.channel.commands;
      this.reqres = _.result(this, 'reqres') || this.channel.reqres;
    },
Run Code Online (Sandbox Code Playgroud)

链接到源

我建议你阅读Wreqr文档了解更多细节.我还建议阅读Marionette注释源 - 它简洁而且记录完备,实际上包括Wreqr源.

NB Marionnette的下一个主要版本v3.x将Wreqr替换为Radio.Radio提供与Wreqr相同的功能和更清晰的API.可以在Marionette 2.x应用程序中使用Radio,如果您要开始使用新应用程序,我建议使用它.