【问题标题】:Titanium Alloy - Create view without controller and access components inside that viewTitanium Alloy - 创建没有控制器的视图并访问该视图内的组件
【发布时间】:2014-04-24 00:12:58
【问题描述】:

我有一个名为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);

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>

然后以 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!"):
});

可以这样做吗?

【问题讨论】:

    标签: titanium appcelerator titanium-alloy


    【解决方案1】:

    是的,您可以通过另一个控制器中的 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() );
    

    【讨论】:

    • 非常感谢 daniula,正是我正在寻找的。虽然我觉得有点不舒服,它不能通过视图访问,而是通过控制器访问。
    【解决方案2】:

    对象通过 ID 暴露在控制器对象上。在overlay.getView() 之前让他们到达那里。

    但是如果你想要的只是点击监听器,为什么不将监听器添加到覆盖中,然后检查源是否是你想要点击的?这将使视图的内部状态从消费视图中抽象出来。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-24
      • 2015-04-19
      • 1970-01-01
      • 2012-10-26
      • 1970-01-01
      相关资源
      最近更新 更多