Question

I have a Titanium Alloy view called overlay.xml that doesn't have a controller. I am creating it in another controller called episode.js and adding it to a container in episode.xml. I'm doing this in order to make overlay.xml into reusable view that can be added anywhere.

For example

episode.js

// create the overlay view
var overlay = Alloy.createController("overlay").getView();
// add it somewhere in episode.xml
$.episodeImage.add(overlay);

Inside overlay.xml I have several components, like buttons and labels, that I'd like to access in Episode View to add event listeners to. For example:

overlay.xml

<Alloy>
    <View id="overlay">
        <Button id="theButton" title="Click Me!" />
        <Label id="theLabel" text="I am a label" />
    </View>
</Alloy>

And then in episode.js for example:

var overlay = Alloy.createController("overlay").getView();
$.episodeImage.add(overlay);

// EXAMPLE: Get the button from overlay.xml and add an event listener
$.theButtonFromOverlayXML.addEventListener("click", function () {
    alert("You clicked the button from overlay.xml!"):
});

Is it possible to do this?

Était-ce utile?

La solution

Yes, you can access views through their ids in another controller. The only need to assign controller object and view object to two different variables:

episode.js

var overlay = Alloy.createController("overlay");

overlay.theButton.addEventListener('click', function() {
    alert('You clicked the button from overlay.xml!');
});

var overlayView = overlay.getView();
$.episodeImage.add(overlayView);
// shorter version
$.episodeImage.add( overlay.getView() );

Autres conseils

The objects are exposed on the controller object by ID. Get them there before you overlay.getView().

But if all you want is click listeners, why not add the listener to overlay, then check if the source is what you want clicked? That would keep the internal state of the view abstracted from the consuming view.

overlay.addEventListener('click', function(evt) {
    if (evt.source.id === 'theButton') {
        alert('You clicked the button from overlay.xml!');
    }
});
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top