我正在学习Marionette.js。我试图运行特定的上下文回调,为此我创建了两个具有不同上下文的回调。
var callback1=new Backbone.Marionette.Callbacks();
callback1.add(function(argu1){alert("This is first context"+argu1.parameters)},"context1");
callback1.add(function(argu1){alert("This is second context"+argu1.parameters)},"context2");
//I want to run only callback which one have context is `context1`.
callback1.run({parameters:"Gran"},"context1");根据我的请求,我应该只得到第一个上下文alert.But,我得到的都是警告框。
我该怎么解决这个问题。
谢谢
发布于 2013-11-04 07:30:25
这实际上不是正确使用Marionette回调。这些回调基本上是一个队列,当运行时,它将调用您添加的所有回调,而不需要任何条件。
第二个参数不是要运行的回调的名称,而是在运行时将应用到它的上下文(、的值)。使用callback.add定义自定义上下文时,将忽略callback.run的第二个param。
在这里查看回调文档:https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.callbacks.md
我想你真正想要的是Marionette命令:https://github.com/marionettejs/backbone.wreqr#commands
使用命令,您可以注册函数,然后可以按名称调用这些函数。此选项的唯一问题是不能提供将应用于命令的单独上下文对象。
如果这是一个要求,那么您应该能够通过使用命令对象来创建这个功能,比如使用_.bind:
var commands = new Backbone.Wreqr.Commands();
var context = { n: 55 };
commands.setHandler("foo", _.bind(function() {
console.log(this); // outputs { n: 55 }
}, context));
commands.execute("foo");如果需要在执行上下文时传递上下文,则可以执行以下操作:
var handler = function(n) {
console.log(this); // outputs { test: "hey" }
console.log(n); // outputs 55
};
commands.setHandler("foo", function(context) {
// only apply the arguments after the context (if any);
handler.apply(context, Array.prototype.slice.apply(arguments).slice(1));
});
commands.execute("foo", { test: "hey" }, 55);希望这能有所帮助!
https://stackoverflow.com/questions/19762240
复制相似问题