function + module.exports

1.3k views Asked by At

I have a problem with module.export on titanium. I tried following https://wiki.appcelerator.org/display/guides/CommonJS+Modules+in+Titanium but it doesn't work at all.

I have 2 little pieces of code. App.js:

var  fenetreBase = Titanium.UI.createWindow({fullscreen:true,backgroundColor:"white",exitOnClose:true});
fenetreBase.open();
var vueimage = new (require('UI/viewimage'))();

vueimage.test();
fenetreBase.add(vueimage);

and viewimage.js in the folder UI.

function viewimage() {
var lavue = Ti.UI.createView({backgroundColor:'red' }); 
var item =...
lavue.add(item...);
return lavue;
}

viewimage.prototype.test = function() {
Ti.API.info("test");
};

module.exports = viewimage;

I have an error saying

Object #<view> has no method 'test' in app.js vueimage.test()

In my mind, I follow the example of "Instantiable Objects" in the wiki above but I may have not understand something. I expect I made a stupid mistake. I tried many other things, each uglier than other and it doesn't work anyway.

Can somebody tell me where the mistake is?

1

There are 1 answers

1
kabomi On BEST ANSWER

your mistake is assuming that you have an instance of viewimage when you run:

var vueimage = new (require('UI/viewimage'))();

you are getting an instance of

var lavue = Ti.UI.createView({backgroundColor:'red' }); 

which doesn't have a test property.

Perhaps you could use an object like this instead:

function viewimage() {
    var result = {};

    var lavue = Ti.UI.createView({backgroundColor:'red' }); 
    var item =...
    lavue.add(item...);
    result.lavue = lavue;
    result.test = function() {
        Ti.API.info("test");
    };
    return result;
}

EDIT

In your App.js:

var vueimage = new (require('UI/viewimage'))();

vueimage.test();
fenetreBase.add(vueimage.lavue);