cilphex
cilphex

Reputation: 6096

How can I get the value of an observable when it changes?

Here's my code:

Dart:

import 'dart:html';
import 'package:polymer/polymer.dart';

@CustomTag('my-thing')
class MyThing extends PolymerElement {
  @observable var val = "Hello, World";

  MyThing.created() : super.created() {}
}

Html:

<link rel="import" href="../../../packages/polymer/polymer.html">

<polymer-element name="my-thing">
  <template>
    <textarea id="asdf" value="{{val}}"></textarea>
    <p>Val is: {{val}}</p>
  </template>
  <script type="application/dart" src="my_thing.dart"></script>
</polymer-element>

You can see that val represents the value of a textarea. What I would like to do is this: when the value of the textarea changes, take the last word inside of it, modify it, and update the textarea with the new text.

For example, if the user types "Hello, world", I might want to recognize the word "world" and replace it with an all caps version, "WORLD".

Do I have to use querySelector to observe the field, separately from my @observable line? I tried this and it did not work:

querySelector('#inputName').onInput.listen(someUpdate);

void someUpdate(Event e) {
  print('changed');
}

I tried it in the MyThing class, I tried it in main, and I tried it outside of anything, and none worked.

I feel like there should be some kind of event I can listen for, setup by using @observable. Is there? If there's nothing I can listen for or no sort of automatic callbacks I can add, how can I change my querySelector line to actually work?

Upvotes: 1

Views: 211

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657466

I don't know if there is something special with textarea but I guess it should fulfill your needs to just add a valChanged method to your MyThing class. This method is called every time val changes.
If you change val inside valChanged you might run into an endless loop though.

valChanged(oldValue, newValue) {
  // do stuff here
}

or you can use the change event

<textarea id="asdf" value="{{val}}" on-change="{{valChangeHandler}}"></textarea>

valChangeHandler(Event e) {
  // here you get the element passed as `e.target`
  // and you can access `val`
}

Upvotes: 2

Related Questions