Reputation: 179
I am learning Marionette.js
. I am trying to run specific context callbacks for that I created 2 callbacks with different contexts.
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");
As per my requirmets, I should get only first context alert.But I am getting both alert boxes.
How can I fix this.
Thanks
Upvotes: 0
Views: 945
Reputation: 836
This actually isn't the correct use of the Marionette Callbacks. These callbacks are basically a queue that when ran will call all of the callbacks that you have added without any criteria.
The second parameter is not the name of the callback that you want to run but the context that will be applied to it (the value of this) when running. When you define a custom context using callback.add, the second param to callback.run is ignored.
Check out the docs on callbacks here: https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.callbacks.md
I think what you really want are Marionette Commands: https://github.com/marionettejs/backbone.wreqr#commands
With commands you can register functions that you can then call by name. The only problem with this alternative is that you cannot provide a separate context object that will be applied to the command.
If that is a requirement then you should be able to create this functionality on your own by using the command object like so using _.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");
If you need to be able to pass the context in when executing it you can do something like this:
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);
Hope this helps!
Upvotes: 2