Best way to get a variable from another class in AS3

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-13 20:14:56

问题


I wonder which one of these methods is the best when trying get a variable from anotherClass to the Main-document-class, and why? 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? 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):

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"));
    }
}

回答1:


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.

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. 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. All the login logic stays within CheckLogin.

Also, using events will allow multiple interested classes to react, without them knowing any of the inside login process.



来源:https://stackoverflow.com/questions/23481117/best-way-to-get-a-variable-from-another-class-in-as3

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