7

I have the following class:

class EventableNumber{

  num _val;

  num get val => _val;

  void set val(num v){

    num oldValue = _val;
    _val = v;
    _controller.add(new NumberChangedEvent(oldValue, v));

  }

  StreamController<NumberChangedEvent> _controller = new StreamController<NumberChangedEvent>();
  Stream<NumberChangedEvent> _stream;
  Stream<NumberChangedEvent> get onChange => (_stream != null) ? _stream : _stream = _controller.stream.asBroadcastStream();

  EventableNumber([num this._val = 0]);

}

Is it possible to overload the = assignment operator? rather than using the val getter and setter to enforce the event to fire when the value changes it would be nice if it could just be done when the user writes myEventableNum = 34 and then myEventableNum first its onChange event, rather than myEventableNum.val = 34.

4

1 回答 1

7

Dart 不允许这样做。

但是,您是否考虑过函数式调用?

基本上,如果您在 EventableNumber 类中定义了一个名为“call”的函数,那么您可以将实例作为函数调用:

myEventableNum(34)

如果你决定走这条路,建议实现 Function 接口:

class EventableNumber implements Function {
...
  void call(val) {...}
...
}

希望这可以帮助 :)

于 2013-11-12T23:25:12.543 回答