Created
January 3, 2012 22:43
-
-
Save benvanstaveren/1557363 to your computer and use it in GitHub Desktop.
JSPL::PerlClass usage example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
use strict; | |
use warnings; | |
package Foobar; | |
use Moose; | |
use JSPL; | |
use Try::Tiny qw/catch try/; | |
has 'foo' => (is => 'rw', isa => 'Num', required => 1, reader => 'get_foo', writer => 'set_foo'); | |
sub fnork { print('I just fnorked', "\n") } | |
sub in_javascript_land { | |
try { | |
JSPL::Context->current; | |
return 1; | |
} catch { | |
return 0; | |
}; | |
} | |
sub onlyFromPerl { | |
my $self = shift; | |
return if($self->in_javascript_land); | |
print('You should only see this when the perl code runs...', "\n"); | |
} | |
package main; | |
use JSPL; | |
use JSPL::PerlClass; | |
use Try::Tiny; | |
my $rt = JSPL::Runtime->new(); | |
my $ctx = $rt->create_context; | |
$ctx->bind_class( | |
name => 'Foobar', | |
package => 'Foobar', | |
constructor => sub { my $pkg = shift; Foobar->new(@_) }, | |
methods => { | |
frob => \&Foobar::fnork, | |
fnork => \&Foobar::fnork, | |
}, | |
properties => { | |
'foo' => { | |
getter => sub { | |
return Foobar::get_foo(@_); | |
}, | |
setter => sub { | |
my $s = shift; | |
my $n = shift; | |
try { | |
Foobar::set_foo(@_); | |
} catch { | |
die '"', $n, '" is not a valid Number', "\n"; | |
}; | |
}, | |
}, | |
} | |
); | |
$ctx->bind_value('say' => sub { print @_, "\n" }); | |
print 'Javascript stuff', "\n"; | |
$ctx->eval(q| | |
Foobar.prototype.frobThisGood = function() { | |
this.frob(); | |
}; | |
var f = new Foobar({ foo: 10 }); | |
say('foo is: ', f.foo); | |
say('Did you just frob?'); | |
f.frob(); | |
say('Do that again...'); | |
f.frobThisGood(); | |
|); | |
print 'And now from Perl', "\n"; | |
# this gets us our object back | |
my $f = $ctx->eval(q|f;|); | |
print('f isa: ', ref($f), "\n"); | |
$f->fnork(); | |
$f->onlyFromPerl(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment