简体   繁体   English

从AS3中的另一个类获取变量的最佳方法

[英]Best way to get a variable from another class in AS3

I wonder which one of these methods is the best when trying get a variable from anotherClass to the Main-document-class, and why? 我不知道尝试将另一个类的变量获取到Main-document-class时,哪种方法最好?为什么? Are there any more, even better ways? 还有更多甚至更好的方法吗?

In example no 1, and the Main-function, can the if-else statement be triggered before the checkLogin function was completely done? 在示例1和Main函数中,是否可以在完成checkLogin函数之前触发if-else语句? Thanks! 谢谢!

My no 1. way 我的第一种方式

public class Main extends MovieClip {

// Declaring other classes.
    private var checkLogin:CheckLogin;

    public function Main() {
        checkLogin = new CheckLogin();
        if(checkLogin.isLoggedIn == true) {
            trace("Is logged in");
        } else {
            trace("Not logged in");
        }
    }   
}

and

public class CheckLogin {

    public var isLoggedIn:Boolean;

    public function CheckLogin() {
        isLoggedIn = false;
    }
}

Or is it a lot better to do it this way, (Way no 2): 还是用这种方法更好((第2种方式):

public class Main extends MovieClip {

    // Declaring other classes.
    private var checkLogin:CheckLogin;

    public function Main() {
        checkLogin = new CheckLogin();
        checkLogin.addEventListener("checkLogin.go.ready", checkLoginReady);
        checkLogin.go();
    }
    public function checkLoginReady(event = null) {
        if(checkLogin.isLoggedIn == true) {
            trace("Is logged in");
        } else {
            trace("Not logged in");
        }
    }
}

and

public class CheckLogin extends EventDispatcher {

    public var isLoggedIn:Boolean;

    public function CheckLogin() {
        isLoggedIn = true;
    }

    public function go() {
        this.dispatchEvent(new Event("checkLogin.go.ready"));
    }
}

Generally, using events will make your code easier to maintain. 通常,使用事件将使您的代码更易于维护。

The login check you describe seems to be instant, so approach number 1 would be ok for such a simple case. 您描述的登录检查似乎是即时的,因此对于这种简单情况,方法1是可以的。

Often the login check (or whatever process) may not be instant, for example if the CheckLogin class sent a server request and waited for the response. 通常,登录检查(或任何过程)可能不是即时的,例如,如果CheckLogin类发送了服务器请求并等待响应。 In this case using events is better. 在这种情况下,使用事件更好。 The Main class can listen for a LOGIN_SUCCESS or LOGIN_FAIL event and handle it when the event occurs. Main类可以侦听LOGIN_SUCCESS或LOGIN_FAIL事件,并在事件发生时进行处理。 All the login logic stays within CheckLogin. 所有登录逻辑都保留在CheckLogin中。

Also, using events will allow multiple interested classes to react, without them knowing any of the inside login process. 同样,使用事件将允许多个感兴趣的类做出反应,而无需知道任何内部登录过程。

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

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