سؤال

I'm trying to create a js module (a js file) in Titanium that would act like a java class with static methods so i can require the class and make use of the methods. The structure is as follows:

var Repository = {
    setProp : function(_args) {
        Ti.App.Properties.setString(_args.name, _args.value);
    },

    getProp : function(_args) {
        var tmp = Ti.App.Properties.getString(_args.name);
        if (tmp)
            return tmp;
        else
            return _args.default_val;
    },

    foo : function () {
    },

    bar : function (error) {
    }

};// end Repository

This is contained in a file called

Repository.js

I tried adding the following lines to the end of the file

function init() {
    return Repository;
};// end function init

module.exports = init;

And in the file in which i wanted to use the functions in Repository, i did the following:

var Repo = require('ui/utility/Repository');
var _name = Repo.getProp({name: 'name', default_val: ''}),

But i get the following error:

Uncaught TypeError: Object function init {return Repository} has no method 'getProp'

Thanks guys

هل كانت مفيدة؟

المحلول

In Javascript, you have created a simple object called Repository. Although you have a function called init(), it will not be called with the require statement.

You do not need the init function at all, just change Repository.js to

module.exports = Repository;

and this object will be available by requiring Repository.js, just like you did!

var Repo = require('ui/utility/Repository');
var _name = Repo.getProp({name: 'name', default_val: ''});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top