【发布时间】:2017-04-10 15:00:17
【问题描述】:
任何人都可以提供一个代码示例,您如何在类内的变量更改上设置观察者?我尝试使用不同的功能(Scalar::Watcher、trigger attribute of Moo)和 OOP 框架(Moo、Mojo::Base)以多种方式实现,但都失败了。
以下是我失败的代码,以便更好地理解我的任务。在此示例中,每次 attr1 更改时我都需要更新 attr2。
使用 Mojo::Base 和 Scalar::Watcher:
package Cat;
use Mojo::Base -base;
use Scalar::Watcher qw(when_modified);
use feature 'say';
has 'attr1' => 1;
has 'attr2' => 2;
has 'test' => sub { # "fake" attribute for getting access to $self
my $self = shift;
when_modified $self->attr1, sub { $self->attr2(3); say "meow" };
};
package main;
use Data::Dumper;
my $me = Cat->new;
$me->attr1;
warn Dumper $me;
say $me->attr1(3)->attr2; # attr2 is still 2, but must be 3
使用 Moo 和触发器:
package Cat;
use Moo;
use Scalar::Watcher qw(when_modified);
use feature 'say';
has 'attr1' => ( is => 'rw', default => 1, trigger => &update() );
has 'attr2' => ( is => 'rw', default => 1);
sub update {
my $self = shift;
when_modified $self->attr1, sub { $self->attr2(3); say "meow" }; # got error here: Can't call method "attr1" on an undefined value
};
package main;
use Data::Dumper;
my $me = Cat->new;
$me->attr1;
warn Dumper $me;
say $me->attr1(3)->attr2;
非常感谢任何建议。
【问题讨论】:
-
Mojo::Base 的问题在于它不应该是一个通用的对象系统。它提供了简单的行为并且非常快。我们始终支持使用 Moo(se) 构建您的 Mojolicious 应用程序?当你想要这样的行为时,那是最好的解决方案!
标签: perl oop watch mojolicious moo