The App.Helpers.Callbacks.new
helper generates a callback object similar to element event listeners. It supports methods like on
and trigger
.
Event Scopes
Periods within event types are treated as "scopes", and all parent scopes are triggered by a child.
For example, triggering the event update.field.name
will trigger any events attached to update.field.name
, update.field
, or update
.
Triggering the event update
will not trigger children like update.field.name
.
var callbacks = App.Helpers.Callbacks.new();
callbacks.on("update", function() {
console.log("Update!");
});
callbacks.on("update.field", function(name) {
console.log("Field Update: " + name);
});
// Outputs: "Update!"
callbacks.trigger("update");
// Outputs: "Update!" and "Field Update: Test"
callbacks.trigger("update.field", "Test");
App.Helpers.Callbacks.new(object = null)
Generate a Callback object with App.Helpers.Callbacks.new()
.
If the optional object
argument is given, the callback method will be bound to the object
when triggered, and you can use this
to refer to object
inside the method.
on(type, method)
Runs the method
callback when type
is triggered.
var callbacks = App.Helpers.Callbacks.new();
callbacks.on("type", function() {
console.log("Triggered!");
});
trigger(type, parameters...)
Runs any callbacks attached to the type
value, passing the parameters given.
var callbacks = App.Helpers.Callbacks.new();
callbacks.on("type", function(one, two) {
console.log("One: " + one);
console.log("Two: " + two);
});
// Outputs "One: 1" and "Two: 2"
callbacks.trigger("type", 1, 2);
trigger_synchronous(type, parameters...)
Runs any callbacks attached to the type
value, waiting for any Promise
values returned by a callback to resolve before running the next callback. If a returned Promise
rejects, subsequent callbacks will not run.
This method is used to manage submission validation methods, like validate
, before_save
, and after_save
, which run synchronously and only trigger if the previous method's callbacks all resolved. The usage is similar to the example below:
submission.callbacks = App.Helpers.Callbacks.new(submission);
submission.callbacks.trigger_synchronous("validate").then(function() {
submission.callbacks.trigger_synchronous("before_save").then(function() {
submission.save().then(function() {
submission.callbacks.trigger_synchronous("after_save");
});
});
});