模块中的访问属性(CommonJS 样式)

Access property within module (CommonJS style)

本文关键字:CommonJS 样式 属性 访问 模块      更新时间:2023-09-26

在Appcelerator Titanium中,我正在创建一个标签,该标签最初设置为某些文本。然后,我添加一个按钮,单击该按钮时将调用scanController模块,该模块需要更改该文本。因此,在scanController中,我在scanView模块中调用了setResultTxt()方法,如下所示。但是什么时候这样做,它说myResultTxt是空的!为什么?

我仍在使用 Titanium SDK 1.7.5,因为我无法升级到较新版本。

这是该问题的完整工作示例:

应用.js

var win = Titanium.UI.createWindow({  
    backgroundColor:'#fff',
    layout:"vertical"
});
win.open();
var module = require('scanView');
module.createScanPage(win);

扫描视图.js

var myResultTxt, theButton;
exports.createScanPage = function(theWindow) {
    myResultTxt = Ti.UI.createLabel({
        text: 'Some initial text',
        top:40,
    });
    theWindow.add(myResultTxt);
    theButton = Ti.UI.createButton({
        title: 'Do something',
        top:20
    });
    theButton.addEventListener('click', function() {
        alert('clicked');
        var b = require('scanController');
        b.startScanning();
    });
    theWindow.add(theButton);
};
exports.setResultText = function(str) {
    myResultTxt.text = str;
};

扫描控制器.js

exports.startScanning = function() {
    var a = require('scanView');
    a.setResultText('My new text');
};

尽管循环引用应该适用于 CommonJS(此线程建议这样做),但我个人避免使用它们,因为您可能会得到意想不到的结果,尤其是使用 Titanium 和不同的平台。

您可以使用回调或事件侦听器,两者都可以在您的情况下使用。

下面是回调解决方案的示例:

扫描视图.js

theButton.addEventListener('click', function() {
     var b = require('scanController');
     // You could pass an existing function as well 
     b.startScanning(function(response) {
         if(response && response.text) {
             myResultTxt.text = response.text;
         }
     });
});

扫描控制器.js

exports.startScanning = function(callback) {
    callback({ text:'My new text'});
};


编辑:
要使 setText 从任何模块中可用,您可以设置一个全局事件侦听器。(我知道有些人认为这种做法很糟糕,主要是因为可能存在内存泄漏,但如果你在你身后清理,这是一个有价值的功能)。

应用.js

Ti.App.addEventListener('app:setScanText', module.setResultText);


扫描控制器.js

exports.startScanning = function() {
    Ti.App.fireEvent('app:setScanText', { text: 'My new text' });
};


扫描视图.js

exports.setResultText = function(response) {
    if(response && response.text) {
        myResultTxt.text = response.text;
    }
};

这是未经测试的。