AS3 Event listeners when data is changed?

99封情书 提交于 2019-12-24 12:06:34

问题


Hopefully you will excuse me if this is a simple/silly question. I started learning action script about 6 days ago and already working on a small project :D

Anyways, there is a property that changes occasionally to reflect the name of a level in a game (object._I._M.text). It could take a minute to change, or a max of two minutes, depending on how fast all players are able to finish the level.

I want to be able to listen for the change in this property to fire off another function. I have found very few answers to this online, and the examples I have found were very incomplete and poorly written. Does anyone know how I could do this?

I have tried ...

theobject._I._M.addEventListener(Event.CHANGE, myfunction);

To no success. Thanks for any help or advice, I am going to get back to learning while I await responses :D


回答1:


I would probably use getters/setters, or just declare one method to change the text of that textfield so that you can dispatch an event every time.

function changeLevel(text:String):void {
   levelTf.text=text;
   dispatchEvent(new Event("levelChange"));
}



回答2:


I'll agree the Adobe docs are a bit "heavy" to look through. A good resource is the kirupa forum.

As for the TextField change event listener, your original code is very close. Here is a good example of how to add an event listener. The basics are:

public class Main extends Sprite {
  // Store a reference to the text field
  // (you're already doing this somewhere, so adapt as you see fit)
  private var inputfield:TextField = new TextField();

  public function Main() {
    // Make sure the field is added to an on-screen Sprite
    addChild(inputfield);

    // Add the event listener.
    // I recommend adding the 'false, 0, true' params. There are lengthy
    // discussions around about this.
    inputfield.addEventListener(Event.CHANGE, changeListener, false, 0, true);
  }

  // This function gets called every time the event is fired.
  private function changeListener (e:Event):void {
    trace("event");
  }
}

Hopefully that gets you started in the right direction.



来源:https://stackoverflow.com/questions/4756138/as3-event-listeners-when-data-is-changed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!