Search code examples
appceleratorappcelerator-titaniumappcelerator-alloy

Appcelerator Alloy ignores platform specific code


I have written the following code:

if (OS_ANDROID) {
    function showDialog() {
        // Android logic
    }

    function closeDialog() {
        // Android logic
    }
}

if (OS_IOS) {
    function showDialog() {
        // iOS logic
    }

    function closeDialog() {
        // iOS logic
    }
}

For some reason when I run on Android it executes the code for iOS. So when I had a look at the generated files in the resources directory I see that generated code just removes the if (OS_ANDROID) and if (OS_IOS) blocks and leaves both codes (iOS and Android) on the file.

Currently I'm running on the emulators, but I'm guessing it should work just the same.


Solution

  • It's not Titanium issue you are running into, rather it's a JavaScript programming error you are doing here, & solution to this error is called as JavaScript's Function Hoisting

    You cannot just simply declare functions inside if-else conditions because if-else is a block & blocks do not contain function declarations.

    That's why Titanium resources files are showing both methods because methods are not allowed to be declared inside if-else, and if you do, then they will be considered as in global scope or more accurately in the parent scope of if-else.

    So, you can make your code work like this:

    function showDialog() {
        if (OS_IOS) {
           // ios logic
    
        } else if (OS_ANDROID) {
           // android logic
        }
    }
    
    function closeDialog() {
        if (OS_IOS) {
           // ios logic
    
        } else if (OS_ANDROID) {
           // android logic
        }
    }