简体   繁体   English

在AS3 / Flash CS5中全局导入类

[英]Import Class Globally in AS3/Flash CS5

I have a project in ActionScript 3, Flash Professional CS5.5, and AIR 3. 我在ActionScript 3,Flash Professional CS5.5和AIR 3中有一个项目。

I have several custom classes that I need to access. 我有几个需要访问的自定义类。 Currently, I am successfully accessing via the traditional method: 目前,我可以通过传统方法成功访问:

import trailcrest.core.core;
var Core:core = new core();

However, I came to a realization in my code...this creates a COPY of the class, and doesn't give access to the original. 但是,我在代码中实现了一个实现...这将创建该类的COPY,并且无法访问原始代码。 This, of course is a problem - I need one symbol's scripts to modify a variable in the class, and another symbol's scripts access that changed variable. 当然,这是一个问题-我需要一个符号的脚本来修改类中的变量,而另一个符号的脚本可以访问更改后的变量。 Obviously, right now, that is not occurring. 显然,现在还没有发生。

How do I do what I am describing? 我该怎么做? Should I somehow create a "public var" for the class (though I need instructions on how to do that...I can't use "public var" within stages or symbols)? 我应该以某种方式为该类创建一个“公共变量”吗(尽管我需要有关如何操作的说明...我不能在阶段或符号中使用“公共变量”)? Is there some way to directly access the class? 有什么方法可以直接访问该类吗?

Help! 救命! And thanks in advance. 并预先感谢。

It is generally considered bad practice to use global variables. 使用全局变量通常被认为是不好的做法。 It usually leads to code that lacks flexibility and easily breaks when ,for instance , you introduce some changes or make modifications. 它通常导致代码缺乏灵活性,并且在例如进行一些更改或修改时容易中断。

import trailcrest.core.core;
var Core:core = new core();

This is fine! 这可以!

If an Object needs to change the value of a property in Core, you simply need to inform Core of the change of value by dispatching an Event. 如果对象需要更改Core中属性的值,则只需要通过调度事件来通知Core值的更改。

 var object:MovieClip = new MovieClip();
 object.dispatchEvent ( property );

In that case, it would seem to make sense for Core to be your Document Class, in which case it would be aware of all the Objects in your app, whether as chidren, grand children etc... 在这种情况下,将Core用作您的文档类似乎很有意义,在这种情况下,它将知道您应用中的所有对象,无论是孩子,大孩子等。

If it's not your Document Class, then you could do... 如果不是您的文档类,那么您可以...

 //In the Document Class
 var Core:core = new Core();
 var object:MovieClip = new MovieClip();

 // CoreEvent being a Custom Event
 object.addEventListener( CoreEvent.CHANGE , changeListener );
 addChild( object );

 //in another part of the Document Class
 //after a value has changed
 object.dispatchEvent ( property );

 //a method of the Document Class
 private function changeListener( event:CoreEvent ):void
 {
      var propNewValue:Object = event.property;
      //If you're using a singe instane of Core in the Document
      //Class, any other symbol can now access the new value.
      core.property = propNewValue;
 }

If objects are created in other parts of your application , you could always pass an instance of Core as a parameter. 如果对象是在应用程序的其他部分中创建的,则始终可以将Core实例作为参数传递。

  //In the Document Class
  var newobject:MovieClip = new CustomClass( core );

Edit 编辑

If you find this answer confusing, you should probably read about OOP's basic principles as well as Event Dispatching in AS3. 如果您发现此答案令人困惑,则可能应该阅读有关OOP的基本原理以及AS3中的事件分发的信息。 Something of interest may be the Signals library , a nice alternative to Event Dispatching. 令人感兴趣的可能是信号库 ,它是事件分派的不错替代方案。

The general idea is to avoid to have your Objects tied up to a Singleton, or any type of Global variables. 总体思路是避免将对象绑定到Singleton或任何类型的Global变量。 An Object , in theory, should only know about itself and you would use Events for Objects to communicate between themselves. 从理论上讲,对象应该只了解自身,并且可以使用对象的事件在它们之间进行通信。

This is nicely accomplished by using Singleton design pattern . 这可以通过使用Singleton设计模式很好地完成。 Here is sample AS3 implementation: 这是示例AS3实现:

package   {

public class SomeClass {

    /** Singleton instance */
    private static var instance : SomeClass;

    /** This instance variable will be accesible globaly by calling it SomeClass.getInstance().somePublicVar */
    public var somePublicVar    : * ;

    /**
     * Get singleton instance of class
     * @return  singleton instance  SomeClass
     */
    public static function getInstance () : SomeClass {
        return SomeClass.instance ? SomeClass.instance : ( SomeClass.instance = new SomeClass() );
    }

}

} }

The best method is to create something called a "singleton." 最好的方法是创建一个称为“单例”的东西。 A singleton is, quite simply, a static class without all the pesky cons of a static class. 简单来说,单例是静态类,没有静态类的所有缺点。 It makes a single instance (or single copy) available globally, which will then act exactly like a regular instance (because it is). 它使全局一个实例(或单个副本)可用,然后它将像常规实例一样工作(因为有)。

A singleton is possible through the use of static variables and functions. 通过使用静态变量和函数,可以实现单例。 A static variable/function is a part of the class , not an instance. 静态变量/函数是的一部分,而不是实例。 As such, there can only be one of each variable (there's only one class) and they are all globally accessible. 因此,每个变量只能有一个(只有一个类),并且它们都可以全局访问。 A good example of static functions and properties is the built-in Math class. 内置的Math类是静态函数和属性的一个很好的例子。 You get the value of Pi like this: 您将获得Pi的价值,如下所示:

Math.PI

not like this: 不像这样:

var math:Math = new Math();
math.PI

As you can see, it's the class that has the method. 如您所见,具有方法的是类。 We can use this to make a singleton by providing a static getInstance() function that will be globally accessible that will always return the same object. 我们可以通过提供一个静态的getInstance()函数来使它成为单例,该函数可以全局访问并始终返回同一对象。 Here's a sample implementation of the singleton: 这是单例的示例实现:

package {

    public class SingletonSample {

        // The singleton instance
        private static sharedSingleton:SingletonSample = null;

        // The constructor. AS3 doesn't allow for private constructors
        // so we have to protect it manually
        public function SingletonSample() {
            if (sharedSingleton != null)
                throw new Error ("SingletonSample cannot be created with the new keyword. Use getInstance() instead.");
        }

        // The method that will get the actual instance
        public function getInstance():SingletonSample {
            if (sharedSingleton == null)
                sharedSingleton = new SharedSingleton();
            return sharedSingleton;
        }

    }

}

Aside from those methods and variables defined in the sample, the rest of the class can be programmed normally. 除了样本中定义的那些方法和变量之外,该类的其余部分都可以正常编程。 Then, when you want to use the class in your code, instead of doing this: 然后,当您想在代码中使用该类时,不要这样做:

var instance:SingletonSample = new SingletonSample();
instance.doAThing(instance.aProperty);

do this: 做这个:

var instance:SingletonSample = SingletonSample.getInstance();
instance.doAThing(instance.aProperty);

In fact, when you're just quickly calling methods, you don't need to create a local variable at all. 实际上,当您只是快速调用方法时,根本不需要创建局部变量。 Just do something like this: 只是做这样的事情:

SingletonSample.getInstance.aQuickFunction();

This is all globally available, provided the SingletonSample class has been imported. 只要已导入SingletonSample类,这在全球范围内都是可用的。 This design pattern makes a great "manager" class, so it will probably fit your needs. 这种设计模式造就了出色的“经理”类,因此很可能会满足您的需求。 Keep in mind, though, singletons are generally not good for actually being manipulatable objects. 但是请记住,单例通常不利于实际操作对象。 Use them as managers that provide references to other things, a sort of "middleman" class, if you will. 如果愿意,可以将它们用作提供对其他事物(一种“中间人”类)的引用的管理器 However, if used properly, they can be a powerful and convenient tool in a programmer's arsenal. 但是,如果使用得当,它们可以成为程序员中强大而便捷的工具。

You can consider using a static class variable, something like: 您可以考虑使用静态类变量,例如:

package trailcrest.core {
    import trailcrest.core.core;
    public class YourCustomClass {
        public static var coreReachableFromAnywhere:Core //THE STATIC VARIABLE FOR CORE
    }
}

Then in your grandchild code: 然后在您的孙代码中:

import trailcrest.core.YourCustomClass;
yourCustomClass.coreReachableFromAnywhere = new Core();
yourCustomClass.coreReachableFromAnywhere.someMethod() ...

Edit 编辑

Of course adding the singleton type of method as was suggested by others would make it even cleaner, I will up-vote their answers as well. 当然,按照其他人的建议添加单例类型的方法将使其变得更加简洁,我也将对他们的答案进行投票。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM