Best way to get a variable from another class in A

2019-09-01 05:30发布

问题:

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.