钛合金 - 在该视图中创建没有控制器和访问组件的视图

shr*_*ans 3 titanium appcelerator titanium-alloy

我有一个名为Titanium Alloy的视图overlay.xml,它没有控制器.我在另一个调用的控制器中创建它episode.js并将其添加到容器中episode.xml.我这样做是为了使overlay.xml可重复使用的视图可以添加到任何地方.

例如

episode.js

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

在里面overlay.xml我有几个组件,比如按钮和标签,我想访问它们Episode View以添加事件监听器.例如:

overlay.xml

<Alloy>
    <View id="overlay">
        <Button id="theButton" title="Click Me!" />
        <Label id="theLabel" text="I am a label" />
    </View>
</Alloy>
Run Code Online (Sandbox Code Playgroud)

然后以episode.js为例:

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!"):
});
Run Code Online (Sandbox Code Playgroud)

是否有可能做到这一点?

dan*_*ula 5

是的,您可以通过其他控制器中的ID访问视图.唯一需要将控制器对象和视图对象分配给两个不同的变量:

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() );
Run Code Online (Sandbox Code Playgroud)