view release on metacpan or search on metacpan
web/javascript/slider.js view on Meta::CPAN
if (!Control) var Control = { };
// options:
// axis: 'vertical', or 'horizontal' (default)
//
// callbacks:
// onChange(value)
// onSlide(value)
Control.Slider = Class.create({
initialize: function(handle, track, options) {
var slider = this;
view all matches for this distribution
view release on metacpan or search on metacpan
deps/hiredis/README.md view on Meta::CPAN
redisAsyncFree(c);
c = NULL;
} else {
appData->context = c;
appData->connecting = 1;
c->data = appData; /* store application pointer for the callbacks */
redisAsyncSetConnectCallback(c, appOnConnect);
redisAsyncSetDisconnectCallback(c, appOnDisconnect);
}
}
deps/hiredis/README.md view on Meta::CPAN
The asynchronous context _should_ hold a *connect* callback function that is called when the connection
attempt completes, either successfully or with an error.
It _can_ also hold a *disconnect* callback function that is called when the
connection is disconnected (either because of an error or per user request). Both callbacks should
have the following prototype:
```c
void(const redisAsyncContext *c, int status);
```
deps/hiredis/README.md view on Meta::CPAN
field in the context can be accessed to find out the cause of the error.
The context object is always freed after the disconnect callback fired. When a reconnect is needed,
the disconnect callback is a good point to do so.
Setting the connect or disconnect callbacks can only be done once per context. For subsequent calls the
api will return `REDIS_ERR`. The function to set the callbacks have the following prototype:
```c
/* Alternatively you can use redisAsyncSetConnectCallbackNC which will be passed a non-const
redisAsyncContext* on invocation (e.g. allowing writes to the privdata member). */
int redisAsyncSetConnectCallback(redisAsyncContext *ac, redisConnectCallback *fn);
int redisAsyncSetDisconnectCallback(redisAsyncContext *ac, redisDisconnectCallback *fn);
```
`ac->data` may be used to pass user data to both callbacks. A typical implementation
might look something like this:
```c
void appOnConnect(redisAsyncContext *c, int status)
{
myAppData *appData = (myAppData*)c->data; /* get my application specific context*/
deps/hiredis/README.md view on Meta::CPAN
}
}
```
### Sending commands and their callbacks
In an asynchronous context, commands are automatically pipelined due to the nature of an event loop.
Therefore, unlike the synchronous API, there is only a single way to send commands.
Because commands are sent to Redis asynchronously, issuing a command requires a callback function
that is called when the reply is received. Reply callbacks should have the following prototype:
```c
void(redisAsyncContext *c, void *reply, void *privdata);
```
The `privdata` argument can be used to curry arbitrary data to the callback from the point where
the command is initially queued for execution.
deps/hiredis/README.md view on Meta::CPAN
If the reply for a command with a `NULL` callback is read, it is immediately freed. When the callback
for a command is non-`NULL`, the memory is freed immediately following the callback: the reply is only
valid for the duration of the callback.
All pending callbacks are called with a `NULL` reply when the context encountered an error.
For every command issued, with the exception of **SUBSCRIBE** and **PSUBSCRIBE**, the callback is
called exactly once. Even if the context object id disconnected or deleted, every pending callback
will be called with a `NULL` reply.
For **SUBSCRIBE** and **PSUBSCRIBE**, the callbacks may be called repeatedly until an `unsubscribe`
message arrives. This will be the last invocation of the callback. In case of error, the callbacks
may receive a final `NULL` reply instead.
### Disconnecting
An asynchronous connection can be terminated using:
deps/hiredis/README.md view on Meta::CPAN
void redisAsyncDisconnect(redisAsyncContext *ac);
```
When this function is called, the connection is **not** immediately terminated. Instead, new
commands are no longer accepted and the connection is only terminated when all pending commands
have been written to the socket, their respective replies have been read and their respective
callbacks have been executed. After this, the disconnection callback is executed with the
`REDIS_OK` status and the context object is freed.
The connection can be forcefully disconnected using
```c
void redisAsyncFree(redisAsyncContext *ac);
```
In this case, nothing more is written to the socket, all pending callbacks are called with a `NULL`
reply and the disconnection callback is called with `REDIS_OK`, after which the context object
is freed.
### Hooking it up to event library *X*
deps/hiredis/README.md view on Meta::CPAN
/* Handle error, in c->err / c->errstr */
}
```
## RESP3 PUSH replies
Redis 6.0 introduced PUSH replies with the reply-type `>`. These messages are generated spontaneously and can arrive at any time, so must be handled using callbacks.
### Default behavior
Hiredis installs handlers on `redisContext` and `redisAsyncContext` by default, which will intercept and free any PUSH replies detected. This means existing code will work as-is after upgrading to Redis 6 and switching to `RESP3`.
### Custom PUSH handler prototypes
view all matches for this distribution
view release on metacpan or search on metacpan
$loop->notify; # tell loop to take note of the timer
}
1 while $flag; # $flag will be set asynchronously
# implement a critical section, uninterrupted by any callbacks
{
$loop->interrupt->scope_block;
# critical section, no watcher callback interruptions
}
L<EV> event loop and runs it in a separate thread. That means it will poll
for events even while your foreground Perl interpreter is busy (you don't
need to have perls pseudo-threads enabled for this either).
Whenever the event loop detecs new events, it will interrupt perl and ask
it to invoke all the pending watcher callbacks. This invocation will be
"synchronous" (in the perl thread), but it can happen at any time.
See the documentation for L<Async::Interrupt> for details on when and how
your perl program can be interrupted (and how to avoid it), and how to
integrate background event loops into foreground ones.
Example: create a section of code where no callback invocations will
interrupt:
{
$EV::Loop::Async::INTERRUPT->scope_block;
# no default loop callbacks will be executed here.
# the loop will not be locked, however.
}
Example: embed the default EV::Async::Loop loop into the default L<EV>
loop (note that it could be any other event loop as well).
to actually handle them.
When Perl finally handles the events, there could be many more ready
file descriptors. To improve latency and performance, you can ask
C<EV::Loop::Async> to loop an additional number of times in the foreground
after invoking the callbacks, effectively doing the polling in the
foreground.
The default is C<0>, meaning that no foreground polling will be done. A
value of C<1> means that, after handling the pending events, it will call
C<< $loop->loop (EV::LOOP_NONBLOCK) >> and handle the resulting events, if
view all matches for this distribution
view release on metacpan or search on metacpan
};
# IO
my $w = EV::io *STDIN, EV::READ, sub {
my ($w, $revents) = @_; # all callbacks receive the watcher and event mask
warn "stdin is readable, you entered: ", <STDIN>;
};
# SIGNALS
=item $active = EV::run [$flags]
=item $active = $loop->run ([$flags])
Begin checking for events and calling callbacks. It returns when a
callback calls EV::break or the flags are nonzero (in which case the
return value is true) or when there are no active watchers which reference
the loop (keepalive is true), in which case the return value will be
false. The return value can generally be interpreted as "if true, there is
more work left to do".
my ($watcher, $revents) = @_;
warn "yeah, STDIN should now be readable without blocking!\n"
};
All watchers can be active (waiting for events) or inactive (paused). Only
active watchers will have their callbacks invoked. All callbacks will be
called with at least two arguments: the watcher and a bitmask of received
events.
Each watcher type has its associated bit in revents, so you can use the
same callback for multiple watchers. The event mask is named after the
corruption.
EV will grab the signal for the process (the kernel only allows one
component to receive a signal at a time) when you start a signal watcher,
and removes it again when you stop it. Perl does the same when you
add/remove callbacks to C<%SIG>, so watch out.
You can have as many signal watchers per signal as you want.
The C<signal_ns> variant doesn't start (activate) the newly created watcher.
=item $w = $loop->check ($callback)
=item $w = $loop->check_ns ($callback)
Call the callback just after the process wakes up again (after it has
gathered events), but before any other callbacks have been invoked.
This can be used to integrate other event-based software into the EV
mainloop: You register a prepare callback and in there, you create io and
timer watchers as required by the other software. Here is a real-world
example of integrating Net::SNMP (with some details left out):
? $event->[Net::SNMP::Dispatcher::_TIME] - EV::now : 0),
0, sub { },
);
};
The callbacks are irrelevant (and are not even being called), the
only purpose of those watchers is to wake up the process as soon as
one of those events occurs (socket readable, or timer timed out). The
corresponding EV::check watcher will then clean up:
our $snmp_check = EV::check sub {
# make the dispatcher handle any new stuff
... not shown
};
The callbacks of the created watchers will not be called as the watchers
are destroyed before this can happen (remember EV::check gets called
first).
The C<check_ns> variant doesn't start (activate) the newly created watcher.
view all matches for this distribution
view release on metacpan or search on metacpan
Object Oriented interface
=item *
Event-based callbacks in server mode
=item *
Internal protocol to take care of all the common transport problems
port => 2345,
)
|| die "ERROR CREATING SERVER: $@\n";
#
# Tell it about the callbacks to call
# on known events
#
$server->setcallback(
data => \&gotdata,
connect => \&connected,
=head1 METHODS
B<[C] = Available to objects created as mode "client">
B<[H] = Available to "hybrid" client objects, as in "the server-side client objects created when a new client connects". These are the objects passed to your server's callbacks. Such hybrid clients behave almost exactly like a normal "client" object...
B<[S] = Available to objects created as mode "server">
=over 4
See close()
=item do_one_loop()
B<[S]> Instructs a server object to "do one loop" and return ASAP. This method needs to be called VERY frequently for a server object to function as expected (either through some sort of loop inside your program if you need to do other things beside...
=item encryption()
B<[C][H]> Returns the name of the module used as the encryption module for this connection, undef if no encryption occurs.
=item start(subref)
B<[S]> Starts a server and does NOT return until the server is stopped via the stop() method. This method is a simple while() wrapper around the do_one_loop() method and should be used if your entire program is dedicated to being a server, and does ...
If you need to concurrently do other things when the server is running, then you can supply to start() the optional reference to a subroutine (very similar to the callback() method). If that is supplied, it will be called every loop. This is very s...
=item stop()
B<[S]> Instructs a running server to stop and returns immediately (does not wait for the server to actually stop, which may be a few seconds later). To check if the server is still running or not use the running() method.
This class does not use the fork() method whatsoever. This means that all it's input/output and multi-socket handling is done via select().
This leads to the following limitation: When a server calls one of your callback subs, it waits for it to return and therefore cannot do anything else. If your callback sub takes 5 minutes to return, then the server will not be able to do anything ...
In other words, make the code in your callbacks' subs' minimal and strive to make it return as fast as possible.
=item Deadlocks
As with any client-server scenario, make sure you engineer how they're going to talk to each other, and the order they're going to talk to each other in, quite carefully. If both ends of the connection are waiting for the other end to say something,...
foreach (keys %para) {
if (ref($para{$_}) ne "CODE") {
$@ = "Callback $_ $para{$_} does not exist";
return 0;
}
$self->{_callbacks}->{$_} = $para{$_};
}
return 1;
}
#
$self->{_clients}->{$clientsock}->{_donotencrypt} = $self->{_donotencrypt};
$self->{_clients}->{$clientsock}->{_donotencryptwith} = $self->{_donotencryptwith};
$self->{_clients}->{$clientsock}->{_donotcompress} = $self->{_donotcompress};
$self->{_clients}->{$clientsock}->{_donotcompresswith} = $self->{_donotcompresswith};
$self->{_clients}->{$clientsock}->{_password} = $self->{_password};
$self->{_clients}->{$clientsock}->{_callbacks} = $self->{_callbacks};
$self->{_clients}->{$clientsock}->{_welcome} = $self->{_welcome};
$self->{_clients}->{$clientsock}->{_selector} = $self->{_selector};
}
}
else {
# This takes a client object and a callback keyword and calls back the associated sub if possible
#
sub _callback {
my $client = shift;
my $type = shift;
if (!$client->{_negotiating} && $client->{_callbacks}->{$type}) {
&{ $client->{_callbacks}->{$type} }($client);
}
}
#
# This sub takes a scalar key
view all matches for this distribution
view release on metacpan or search on metacpan
www/edgeexpress/jscript/SpryAssets/SpryData.js view on Meta::CPAN
Spry.Data.HTTPSourceDataSet.prototype.recalculateDataSetDependencies = function()
{
this.hasDataRefStrings = false;
// Clear all old callbacks that may have been registered.
var i = 0;
for (i = 0; i < this.dataSetsForDataRefStrings.length; i++)
{
var ds = this.dataSetsForDataRefStrings[i];
view all matches for this distribution
view release on metacpan or search on metacpan
lib/Eixo/Docker/RequestRawStream.pm view on Meta::CPAN
#
# We encapsulate a callback to send commands
#
if($self->args->{stdin}){
# return 2 callbacks,
# 1 to send messages to docker ,
# 2 to receive response|ack
(
sub {
view all matches for this distribution
view release on metacpan or search on metacpan
lib/Elastic/Model/Index.pm view on Meta::CPAN
$index->reindex( 'myapp_v2', on_conflict => 'IGNORE' );
Similarly, you can pass an C<on_error> handler which will handle other errors,
or all errors if no C<on_conflict> handler is defined.
See L<Search::Elasticsearch::Bulk/Using-callbacks> for more.
=item uid_on_conflict / uid_on_error
These work in the same way as the C<on_conflict> or C<on_error> handlers,
but are passed to L</repoint_uids()> if C<repoint_uids> is true.
lib/Elastic/Model/Index.pm view on Meta::CPAN
=head2 doc_updater()
$coderef = $index->doc_updater( $doc_updater, $uid_updater );
L</doc_updater()> is used by L</reindex()> and L</repoint_uids()> to update
the top-level doc and any UID attributes with callbacks.
The C<$doc_updater> receives the C<$doc> as its only attribute, and should
return the C<$doc> after making any changes:
$doc_updater = sub {
view all matches for this distribution
view release on metacpan or search on metacpan
lib/Emacs/EPL.pm view on Meta::CPAN
sub print_stuff {
my $callback = shift;
# Optimize obviously non-circular cases.
if ($callback eq 'unref') {
# XXX all other callbacks take a single arg.
print( "(epl-cb-unref");
print( " $_") for @{$_[0]};
print( ")");
}
elsif (! (tied ($_[0]) || ref ($_[0]))) {
view all matches for this distribution
view release on metacpan or search on metacpan
lisp/contrib/tabbar.el view on Meta::CPAN
groups)))
buffers)
(tabbar-buffer-cleanup-tabsets buffers)
current-group))
;;; Tab bar callbacks
;;
(defvar tabbar-buffer-group-mode nil
"Display tabs for group of buffers, when non-nil.")
(make-variable-buffer-local 'tabbar-buffer-group-mode)
view all matches for this distribution
view release on metacpan or search on metacpan
2.093070 2009-11-03
improve handling of header and body encoding
2.091920 2009-07-10
add missing (test) prereq Test::Deep
fix cid_for callbacks to exclude the content-id brackets (RT 47787)
(reported by Jason Taylor; thanks!)
2.091410 2009-05-20
documentation improvements
now packaged by Dist::Zilla
view all matches for this distribution
view release on metacpan or search on metacpan
lib/Encode/JavaScript/UCS.pm view on Meta::CPAN
use strict;
use 5.8.1;
our $VERSION = '0.01';
use base qw(Encode::Encoding);
use Encode 2.12 (); # for callbacks
__PACKAGE__->Define('JavaScript-UCS');
sub decode($$;$){
my ($obj, $buf, $chk) = @_;
view all matches for this distribution
view release on metacpan or search on metacpan
lib/EntityModel/Storage.pm view on Meta::CPAN
=cut
=head2 register
Register with L<EntityModel> so that callbacks trigger when further definitions are loaded/processed.
The base storage engine doesn't provide any callbacks - but we define the method anyway so that we don't
need to check for ->can.
=cut
sub register {
lib/EntityModel/Storage.pm view on Meta::CPAN
Each of these applies to a single entity instance only. Since they operate on a callback
basis, multiple operations can be aggregated if desired:
select * from storage where id in (x,y,z)
Two callbacks are required for each of the above operations:
=over 4
=item * on_complete - the operation completed successfully and the data is guaranteed to
have been written to storage. The strength of this guarantee depends on the storage engine
view all matches for this distribution
view release on metacpan or search on metacpan
lib/Env/ShellWords.pm view on Meta::CPAN
those variables without doing space quoting and other messy mucky stuff.
The intent is to use this from L<alienfile> to deal with hierarchical
prerequisites.
You can provide split and join callbacks when you tie:
use Env::ShellWords;
# split on any space, ignore quotes
tie my @FOO, 'Env::ShellWords',
sub { split /\s+/, $_[0] },
view all matches for this distribution
view release on metacpan or search on metacpan
xt/author/pod_spelling_system.t view on Meta::CPAN
TODO
filename
filenames
login
callback
callbacks
standalone
VMS
hostname
hostnames
TCP
view all matches for this distribution
view release on metacpan or search on metacpan
$Eobj::globalobject=();
unless ($Eobj::eobjflag) {
$Eobj::eobjflag = 1; # Indicate that this clause has been run once
$Eobj::errorcrawl='system';
$Eobj::callbacksdepth = 0; # This indicates when callbacks are going on.
undef $Eobj::wrong_flag;
#For unloaded classes: Value is [classfile, parent class, first-given classname].
%Eobj::classes = ('PL_hardroot', 1);
%Eobj::objects = ();
Constant properties
=item *
Magic callbacks: How to make properties depend on each other.
=item *
Setting up properties during object creation with new()
view all matches for this distribution
view release on metacpan or search on metacpan
%% @spec stop() -> ok
%% @doc Stop the reloader.
stop() ->
gen_server:call(?MODULE, stop).
%% gen_server callbacks
%% @spec init([]) -> {ok, State}
%% @doc gen_server init, opens the server in an initial state.
init([]) ->
{ok, TRef} = timer:send_interval(timer:seconds(1), doit),
view all matches for this distribution
view release on metacpan or search on metacpan
xt/author/pod_spelling_system.t view on Meta::CPAN
TODO
filename
filenames
login
callback
callbacks
standalone
VMS
hostname
hostnames
TCP
view all matches for this distribution
view release on metacpan or search on metacpan
lib/Event/ExecFlow/Callbacks.pm view on Meta::CPAN
Event::ExecFlow::Callbacks - Callbacks attached to jobs
=head1 SYNOPSIS
#-- Create a new Callbacks object
my $callbacks = Event::ExecFlow::Callbacks->new (
sub { print "sub called\n" },
sub { print "another sub of this called\n" },
);
#-- Attach callbacks to a job
$job->set_pre_callbacks($callbacks);
#-- Add more subs
$callbacks->add(sub { print "a sub added later\n" });
$callbacks->prepend(sub { print "a sub prepended to the list of subs } );
#-- the execute() methods is executed later by Event::ExecFlow
$callbacks->execute($job);
=head1 DESCRIPTION
This class represents one or more closures which can be attached as
callbacks to an Event::ExecFlow::Job.
=head1 OBJECT HIERARCHY
Event::ExecFlow
view all matches for this distribution
view release on metacpan or search on metacpan
lib/Event/File/tail.pm view on Meta::CPAN
happens.
On the other hand, if you are not using Event for anything else in your program,
this might not be a desired situation.
C<sweep> can be called them to check if some event has happened or not.
If it has it will execute all the pending callbacks and then return (as opposed
from C<loop>). So, long loops might be a good place to use it.
=head1 IMPLEMENTATION
Event::File::tail is a fake watcher in the Event point of view. On the other hand, it
view all matches for this distribution
view release on metacpan or search on metacpan
- make sure that Test::Pod and Test::Pod::Coverage are
installed in the required minimum versions
(thanks to Ricardo Signes <rjbs AT cpan DOT org>)
0.08 Wed Jul 6 10:10:18 CEST 2005
- additional arguments passed to the event-callbacks
weren't freed due to a spurious reference count
incrementation
(spotted by Thomas Yandell <tom AT vipercode DOT com>)
0.07 Sun Jun 5 11:05:57 CEST 2005
- Makefile.PL should honor @ARGV
- some Win32 fixes for Lib.xs
(both patches via rt.cpan.org; there was no name attached to them)
0.02 Fri Aug 27 08:22:38 CEST 2004
- the event callbacks were called without the event-type
argument. Now they receive this additional arg.
0.01 Sat Aug 14 07:30:14 2004
- original version; created by h2xs 1.23 with options
-O -b 5.6.0 -n Event::Lib /usr/local/include/event.h
view all matches for this distribution
view release on metacpan or search on metacpan
lib/Event/RPC/Message/SerialiserBase.pm view on Meta::CPAN
=head1 DESCRIPTION
This module implements universal FREEZE/THAW methodes
for JSON and CBOR based message format classes. Unfortunately
these modules can't take callbacks for these tasks but
require to pollute UNIVERSAL namespace for this, so when
loading several modules overriding these methodes by each
other throw warnings. This module exist just to prevent these.
=head1 AUTHORS
view all matches for this distribution
view release on metacpan or search on metacpan
lib/Event/Stats.pm view on Meta::CPAN
converts a *desired* time interval into an *available* time interval.
Units are in seconds.
=item $elapse = total_time($sec)
Due to long-running callbacks, measurement intervals may take longer
than expected. This function returns the actual clock-time for a
given measurement interval.
=item ($rans, $dies, $elapse) = idle_time($sec)
view all matches for this distribution
view release on metacpan or search on metacpan
1.10 2008-01-15
- min perl 5.006
- Skip bogus_fd test on darwin. Reported by schwern@pobox.com.
- Jerry D. Hedden <jdhedden@cpan.org> and Ãvar Arnfjörð
Bjarmason <avarab@gmail.com> correctly diagnosed that a recent
change in perl (#31130, FETCH/STORE/LENGTH callbacks for numbered capture
variables) caused $1 to loose its read-only-ness hence breaking test 6.
Zefram <zefram@fysh.org> suggested using $$ instead. I have not tested
this patch but it seems trivial enough.
1.09 2007-05-22
0.08 1998-08-14
- C rewrite
0.07 1998-08-05
- test callbacks
- doc queuing
- remove debugging
0.06 1998-07-24
- parameterise register method so 'check' not fixed method but callback
- doc priorities
- doc callbacks
0.05 1998-07-20
- queuing, waiting
- Status method
view all matches for this distribution
view release on metacpan or search on metacpan
lib/Evented/API/Engine.pm view on Meta::CPAN
conjunction with some top-level module.
=head2 Event management
API Engine is I<Evented> in that it tracks all
L<Evented::Object> callbacks attached
from within modules and automatically removes them upon unloading. This allows
you to employ events excessively without constantly worrying about their
eventual disposal.
=head1 METHODS
view all matches for this distribution
view release on metacpan or search on metacpan
lib/Evented/Configuration.pm view on Meta::CPAN
Now assume you have a named block of type C<myBlock> with name C<myName>. If you changed
the key C<myKey> in C<myBlock:myName>, Evented::Configuration would fire event
C<change:myBlock/myName:myKey>.
However, it is recommended that you use the C<-E<gt>on_change()> method rather than
directly attaching event callbacks. This will insure compatibility for later versions that
could possibly change the way events are fired.
=head1 SEE ALSO
=over 4
view all matches for this distribution
view release on metacpan or search on metacpan
lib/Evented/Object.pm view on Meta::CPAN
$priority = 'nan';
# nan priority indicates it should be determined at a later time.
}
# add the callback.
my $callbacks = $event_store->{$event_name}{$priority} ||= [];
push @$callbacks, my $cb = {
%opts,
code => $code,
caller => \@caller
};
lib/Evented/Object.pm view on Meta::CPAN
);
return $cb;
}
# ->register_callbacks()
#
# attaches several event callbacks at once.
#
sub register_callbacks {
my $eo = shift;
return map { $eo->register_callback(%$_, _caller => caller) } @_;
}
##########################
lib/Evented/Object.pm view on Meta::CPAN
##########################
# ->delete_callback(event_name => 'callback.name')
# ->delete_event('event_name')
#
# deletes an event callback or all callbacks of an event.
# returns a true value if any events were deleted, false otherwise.
# more specifically, it returns the number of callbacks deleted.
#
sub delete_callback {
my ($eo, $event_name, $name, $caller) = @_;
my @caller = $caller && ref $caller eq 'ARRAY' ? @$caller : caller;
my $amount = 0;
my $event_store = _event_store($eo);
# event does not have any callbacks.
return 0 unless $event_store->{$event_name};
# if no callback is specified, delete all events of this type.
if (!$name) {
$amount = scalar keys %{ $event_store->{$event_name} };
delete $event_store->{$event_name};
_monitor_fire($caller[0], delete_event => $eo, $event_name);
return $amount;
}
# iterate through callbacks and delete matches.
PRIORITY: foreach my $priority (keys %{ $event_store->{$event_name} }) {
my $callbacks = $event_store->{$event_name}{$priority};
my @goodbacks;
CALLBACK: foreach my $cb (@$callbacks) {
# don't want this one.
if (ref $cb ne 'HASH' || $cb->{name} eq $name) {
$amount++;
next CALLBACK;
}
push @goodbacks, $cb;
}
# no callbacks left in this priority.
if (!scalar @goodbacks) {
delete $event_store->{$event_name}{$priority};
next PRIORITY;
}
# keep these callbacks.
@$callbacks = @goodbacks;
}
return $amount;
}
# ->delete_all_events()
#
# deletes all the callbacks of EVERY event.
# useful when you're done with an object to ensure any possible self-referencing
# callbacks are properly destroyed for garbage collection to work.
#
sub delete_all_events {
my ($eo, $amount) = (shift, 0);
my $event_store = _event_store($eo) or return;
ref $event_store eq 'HASH' or return;
lib/Evented/Object.pm view on Meta::CPAN
$eo = $obj or return;
($event_name, @args) = ($eo_maybe, @$set);
}
# add to the collection.
my ($callbacks, $names) =
_get_callbacks($eo, $event_name, @args);
$collection->push_callbacks($callbacks, $names);
}
return $collection;
}
lib/Evented/Object.pm view on Meta::CPAN
prepare_together(@_)->fire(caller => [caller 1]);
}
# ->fire_once()
#
# prepares an event, fires it, and deletes all callbacks afterward.
#
sub fire_once {
my ($eo, $event_name, @args) = @_;
# fire with this caller.
lib/Evented/Object.pm view on Meta::CPAN
# add_class_monitor()
#
# set the monitor object of a class.
#
# TODO: honestly class monitors need to track individual callbacks so that the
# monitor is notified of all deletes of callbacks added by the class being
# monitored even if the delete action was not committed by that package.
#
sub add_class_monitor {
my ($pkg, $obj) = @_;
lib/Evented/Object.pm view on Meta::CPAN
}
# fetch a callback from its name.
sub _get_callback_named {
my ($eo, $event_name, $callback_name) = @_;
foreach my $callback (@{ _get_callbacks($eo, $event_name) }) {
return $callback if $callback->[2]{name} eq $callback_name
}
return;
}
# fetches callbacks of an event.
# internal use only.
sub _get_callbacks {
my ($eo, $event_name, @args) = @_;
my (%callbacks, %callback_names);
# start out with two stores: the object and the package.
my @stores = (
[ $event_name => $eo->{$events} ],
[ $event_name => _event_store(blessed $eo) ]
lib/Evented/Object.pm view on Meta::CPAN
# delete listeners if necessary.
splice @$listeners, $_, 1 foreach @delete;
}
# add callbacks from each store.
foreach my $st (@stores) {
my ($event_name, $event_store) = @$st;
my $store = $event_store->{$event_name} or next;
foreach my $priority (keys %$store) {
lib/Evented/Object.pm view on Meta::CPAN
# add each callback set. inject callback name.
foreach my $cb_ref (@{ $store->{$priority} }) {
my %cb = %$cb_ref; # make a copy
$cb{id} = "$group_id/$cb{name}";
$callbacks{ $cb{id} } = [ $priority, $group, \%cb ];
$callback_names{$group_id}{ $cb{name} } = $cb{id};
}
}
}
return wantarray ? (\%callbacks, \%callback_names) : \%callbacks;
}
# fire a class monitor event.
sub _monitor_fire {
my ($pkg, $event_name, @args) = @_;
lib/Evented/Object.pm view on Meta::CPAN
sub del;
sub fire;
BEGIN {
*register_event = *register_callback;
*register_events = *register_callbacks;
*delete_event = *delete_callback;
*on = *register_callback;
*del = *delete_callback;
*fire = *fire_event;
}
1;
=head1 NAME
B<Evented::Object> - base class which allows you to attach callbacks to
objects and then fire events on them.
=head1 SYNOPSIS
package Person;
lib/Evented/Object.pm view on Meta::CPAN
=head1 DESCRIPTION
B<I doubt your objects have ever been this evented in your entire life.>
Evented::Object supplies an (obviously objective) interface to store and manage
callbacks for events, fire events upon objects, and more.
Evented::Object allows you to attach event callbacks to an object
(i.e., a blessed hash reference) and then fire events on that object. Event
fires are much like method calls, except that there can be many responders.
Whereas many event systems involve globally unique event names, Evented::Object
allows you to attach events on specific objects. The event callbacks,
priority options, and other data are stored within the object itself.
=head1 MANAGING CALLBACKS
The Evented::Object package provides several convenient methods for managing an
lib/Evented/Object.pm view on Meta::CPAN
=head2 $eo->register_callback($event_name => \&callback, %options)
Attaches an event callback the object.
When the specified event is fired, each
of the callbacks registered using this method will be called by descending
priority order (numerically higher priority numbers are called first.)
$eo->register_callback(myEvent => sub {
...
}, name => 'some.callback', priority => 200);
lib/Evented/Object.pm view on Meta::CPAN
...
}, 'some.callback, priority => 200);
See the above method specification for parameters and supported options.
=head2 $eo->register_callbacks(@events)
Registers several event callbacks at once.
The arguments should be a list of hash
references. These references take the same options as
C<< ->register_callback() >>. Returns a list of return values in the order that
the events were specified.
$eo->register_callbacks(
{ myEvent => \&my_event_1, name => 'cb.1', priority => 200 },
{ myEvent => \&my_event_2, name => 'cb.2', priority => 100 }
);
B<Parameters>
lib/Evented/Object.pm view on Meta::CPAN
=back
=head2 $eo->delete_event($event_name)
Deletes all callbacks registered for the supplied event.
Returns number of callbacks deleted, false if none.
$eo->delete_event('myEvent');
B<Parameters>
lib/Evented/Object.pm view on Meta::CPAN
=back
=head2 $eo->delete_all_events()
Deletes all events and all callbacks from the object.
If you know that an
evented object will no longer be used in your program, by calling this method
you can be sure that no cyclical references from within callbacks will cause the
object to be leaked.
=head1 FIRING EVENTS
=head2 $eo->fire_event($event_name => @arguments)
lib/Evented/Object.pm view on Meta::CPAN
B<$event_name> - name of the event being fired.
=item *
B<@arguments> - I<optional>, list of arguments to pass to event callbacks.
=back
=head2 $eo->fire_once($event_name => @arguments)
Fires the specified event, calling each callback that was registered with
C<< ->register_callback() >> in descending order of their priorities.
Then, all callbacks for the event are deleted. This method is useful for
situations where an event will never be fired more than once.
Returns the L<fire object|Evented::Object::EventFire>.
$eo->fire_once('some_event');
$eo->fire_event(some_event => $some_argument, $some_other_argument);
# the second does nothing because the first deleted the callbacks
B<Parameters>
=over
lib/Evented/Object.pm view on Meta::CPAN
B<$event_name> - name of the event being fired.
=item *
B<@arguments> - I<optional>, list of arguments to pass to event callbacks.
=back
=head2 $eo->fire_events_together(@events)
lib/Evented/Object.pm view on Meta::CPAN
=head2 $eo->prepare_event(event_name => @arguments)
Prepares a single event for firing.
Returns an L<Evented::Object::Collection> representing the pending callbacks.
# an example using the fire option return_check.
$eo->prepare_event(some_event => @arguments)->fire('return_check');
=head2 $eo->prepare_together(@events)
The preparatory method equivalent to C<< ->fire_events_together >>.
Returns an L<Evented::Object::Collection> representing the pending callbacks.
=head2 $eo->prepare(...)
A smart method that uses the best guess between C<< ->prepare_event >> and
C<< ->prepare_together >>.
lib/Evented/Object.pm view on Meta::CPAN
Rather than attaching an event callback to every cow, you can instead make the
farm a listener of the cow. Then, you can attach a single callback to your farm.
If your cow's event for mooing is C<moo>, your farm's event for any mooing is
C<cow.moo>.
When an event is fired on an object, the same fire object is used for callbacks
belonging to both the evented object and its listening objects. Therefore,
callback names should be unique not only to the listener object but to the
object being listened on as well.
You should also note the values of the
lib/Evented/Object.pm view on Meta::CPAN
B<< $fire->object >> - object being listened to; i.e. C<$cow> (NOT C<$farm>)
=back
This also means that stopping the event from a listener object will cancel
I<all> remaining callbacks.
=head2 $eo->add_listener($other_eo, $prefix)
Makes the passed evented object a listener of this evented object.
lib/Evented/Object.pm view on Meta::CPAN
=head1 CLASS MONITORS
An evented object can be registered as a "monitor" of a specific class/package.
I<All> event callbacks that are added from that class to I<any> evented object
of I<any> type will trigger an event on the monitor object.
An example scenario of when this might be useful is an evented object for
debugging all events being registered by a certain package. It would log all of
them, making it easier to find a problem.
lib/Evented/Object.pm view on Meta::CPAN
Fires multiple events at the same time.
This allows you to fire multiple similar
events on several evented objects at the same time. It essentially pretends that
the callbacks are all for the same event and all on the same object.
It follows priorities throughout all of the events and all of the objects, so it
is ideal for firing similar or identical events on multiple objects.
The same L<fire object|Evented::Object::EventFire> is used throughout.
This means that callback names must unique among all of these
objects and events. It also means that stopping an event from any callback will
cancel all remaining callbacks, regardless to which event or which object they
belong.
The function takes a list of array references in the form of:
C<< [ $evented_object, event_name => @arguments ] >>
lib/Evented/Object.pm view on Meta::CPAN
Alias for C<< $eo->register_callback() >>.
=head2 $eo->register_events(...)
Alias for C<< $eo->register_callbacks() >>.
=head2 $fire->eo
Alias for C<< $fire->object >>.
view all matches for this distribution