Форум Flasher.ru

Форум Flasher.ru (http://www.flasher.ru/forum/index.php)
-   ActionScript 3.0 (http://www.flasher.ru/forum/forumdisplay.php?f=83)
-   -   Передача переменной между уровнями (http://www.flasher.ru/forum/showthread.php?t=149530)

RomECH 27.01.2011 02:20

Передача переменной между уровнями
 
Объект (мувиклип) должен увеличить некую числовую переменную верхнего уровня. То есть, какой код писать в главном и дочернем объекте?
AS3

ChuwY 27.01.2011 11:41

Код AS3:

package {
  import flash.display.Sprite;
  import flash.display.MovieClip;
 
  public class Test extends Sprite {
    private var _counter : int;
    private var _child  : Child;
    public function Test() {
      _child = new Child();
    addChild(_child); // факультативно
    _child.addEventListener(CounterEvent.INC_COUNTER, incCounterHandler);
    }
 
    private function incCounterHandler(event : CounterEvent):void{
      _counter++;
      trace("counter = " + _counter);
    }
  }
}
 
import flash.utils.setInterval;
import flash.events.Event;
import flash.display.MovieClip;
import flash.events.MouseEvent;
 
internal class Child extends MovieClip{
  public static const CHILD_DEF_WIDTH : int = 100;
  public static const CHILD_DEF_HEIGTH : int = 100;
  private var _intervalIdx : int;
  public function Child(){
    _intervalIdx = setInterval(dispatch, 1000);
    initGraphic();
  }
 
  private function initGraphic():void{
    graphics.beginFill(0x0, 0.5);
    graphics.drawRect(0, 0, CHILD_DEF_WIDTH, CHILD_DEF_HEIGTH);
    addEventListener(MouseEvent.CLICK, clickHandler);
  }
 
  private function clickHandler(event : MouseEvent):void{
    dispatch();
  }
 
  private function dispatch():void{
    dispatchEvent(new CounterEvent(CounterEvent.INC_COUNTER));
  }
}
 
internal class CounterEvent extends Event{
  public static const INC_COUNTER : String = "increment_counter";
  public function CounterEvent(type : String, bubbles : Boolean = false, cancelable : Boolean = false){
  super(type, bubbles, cancelable);
  }
}

setInterval для того, чтобы обозначить, что в общем-то все равно, мувиклип ли дочерний объект или нет


или так, что уже не очень хорошо, так как потомок вовсе не обязан знать о родителе:

Код AS3:

package {
  import flash.display.Sprite;
  import flash.display.MovieClip;
 
  public class Parent extends Sprite {
    private var _counter : int;
    private var _child  : Child;
    public function Parent() {
      _child = new Child();
      addChild(_child); // факультативно
    }
 
    public function incCounter():void{
      _counter++;
      trace("counter = " + _counter);
    }
  }
}
 
import flash.utils.setInterval;
import flash.events.Event;
import flash.display.MovieClip;
import flash.events.MouseEvent;
 
internal class Child extends MovieClip{
  public static const CHILD_DEF_WIDTH : int = 100;
  public static const CHILD_DEF_HEIGTH : int = 100;
  private var _intervalIdx : int;
  public function Child(){
    _intervalIdx = setInterval(incParentCounter, 1000);
    initGraphic();
  }
 
  private function initGraphic():void{
    graphics.beginFill(0x0, 0.5);
    graphics.drawRect(0, 0, CHILD_DEF_WIDTH, CHILD_DEF_HEIGTH);
    addEventListener(MouseEvent.CLICK, clickHandler);
  }
 
  private function clickHandler(event : MouseEvent):void{
    incParentCounter();
  }       
 
  private function incParentCounter():void{
    var currParent : Parent = parent as Parent;
    if(currParent){
      currParent.incCounter();
    }
  }
}

или вот так, что тоже не очень хорошо по той же причине, но подойдет не только для дисплейобжектов


Код AS3:

package {
  import flash.display.Sprite;
  import flash.display.MovieClip;
 
  public class Parent extends Sprite {
    private var _counter : int;
    private var _child  : Child;
    public function Parent() {
      _child = new Child(this);
      addChild(_child); // факультативно
    }
 
    public function incCounter():void{
      _counter++;
      trace("counter = " + _counter);
    }
  }
}
 
import flash.utils.setInterval;
import flash.events.Event;
import flash.display.MovieClip;
import flash.events.MouseEvent;
 
internal class Child extends MovieClip{
  public static const CHILD_DEF_WIDTH : int = 100;
  public static const CHILD_DEF_HEIGTH : int = 100;
  private var _intervalIdx : int;
  private var _parent : Parent;
  public function Child(parent : Parent){
    _intervalIdx = setInterval(incParentCounter, 1000);
    initGraphic();
    _parent = parent;
  }
 
  private function initGraphic():void{
    graphics.beginFill(0x0, 0.5);
    graphics.drawRect(0, 0, CHILD_DEF_WIDTH, CHILD_DEF_HEIGTH);
    addEventListener(MouseEvent.CLICK, clickHandler);
  }
 
  private function clickHandler(event : MouseEvent):void{
    incParentCounter();
  }       
 
  private function incParentCounter():void{
    if(_parent){
      _parent.incCounter();
    }
  }
}


tsarapkabel 27.01.2011 16:41

Сейчас тупость спрошу, но зачем дитя расширяет MovieClip? Чем Sprite не угодил?

ChuwY 27.01.2011 17:16

От нечего делать :) Вроде как, разница минимальна по занимаемой памяти со спрайтом, а тут еще и условие такое
Цитата:

Объект (мувиклип) должен увеличить некую числовую переменную верхнего уровня.

tsarapkabel 27.01.2011 18:32

А, да, не обратил внимание на мувиклип в условии. :quiet:


Часовой пояс GMT +4, время: 21:55.

Copyright © 1999-2008 Flasher.ru. All rights reserved.
Работает на vBulletin®. Copyright ©2000 - 2024, Jelsoft Enterprises Ltd. Перевод: zCarot
Администрация сайта не несёт ответственности за любую предоставленную посетителями информацию. Подробнее см. Правила.