I am triggering a custom event on an element using jQuery and I want the event handler to be able to pass data (in the form of an object) back to the method that called it. The trigger and the handler are in different scopes and files and cannot be merged or shared in a conventional manner. (The trigger method is part of a utility library I am writing and the event handler is part of my front-end view template).
I know this code doesn't work, but I am writing it to kind of illustrate what I am hoping to try. The pattern is based of of work I have done in .NET.
var data = { foo: 'bar' }
element.trigger('some-event', data)
if(data.foo != 'bar')
alert('someone changed foo!')
And the handler...
element.bind('some-event', function(event, data)
{
if(some_condition)
data.foo = 'biz'
});
The specific implementation is not terrible important to me as long as I don't have rearrange my code to stick both the trigger
and the bind
in the same scope.
How do I get return value back from my event handler?
EDIT
To provide a little more context, the triggering method is responsible for obtaining and processing data, and finally rendering it out as markup to the page. Before it does that, it raises the custom event with the same processed data
object so that other components of the app can have the chance to do something with the processed data.
In certain cases, it would be beneficial for the event handlers to modify that set of data, or event signal to the triggering method that the data has already been handled and does not need additional processing or rendering.
Something like below. In this example, the handler might change the way the data is displayed based upon some property value. It may also choose to render the data out a different way (e.g. input
) rather than the default rendering in the triggering function (e.g. label
).
This implementation is an example, but the end goals of returning an object from the handler, or modifying the data in the handler such that the triggering method can access it are common to my actual project.
var data = load_data();
element.trigger('loading_data', data);
if(data.abort_render!==true)
{
element.append('<label>Foo</label>')
element.append('<span>' + data.foo + '</span>')
}
And the handler...
element.bind('loading-data', function(event, data)
{
if(data.is_password == true)
{
data.foo = '*******' //changed property persisted to triggering method and processed normally
}
if(data.type == 'abc')
{
element.append('<input value="' + data.foo + '"/>');
data.abort_render = true; //signals to the triggering method that it should not render the data to the page
}
}