I'm having trouble importing the i18n library included in Ubuntu.Components 0.1 for use in a JS file. I initially ran into my question/problem while hacking on the 'Clock' Ubuntu Touch core app, but I was able to reproduce the behavior using a much simplified code snippet, so I've pasted that below.
When I run this code on my 14.04 desktop using the UbuntuSDK, I get the error message:
CurrencyConverter/ConverterUtils.js:5: TypeError: Property 'tr' of object [object Object] is not a function
It appears that either I'm referencing the function using the wrong syntax, or there's something wrong with my import syntax.
CurrencyConverter.qml
import QtQuick 2.0
import Ubuntu.Components 0.1
import "ConverterUtils.js" as Utils
MainView {
id: root
applicationName: "CurrencyConverter"
width: units.gu(100)
height: units.gu(75)
property real margins: units.gu(2)
property real buttonWidth: units.gu(9)
Page {
title: Utils.getTitle()
}
}
ConverterUtils.js
.pragma library
.import Ubuntu.Components 0.1 as Foo
function getTitle() {
return i18n.tr("Currency Converter");
}
Notes
1) The ".pragma library" line (to the best of my understanding) is there to say: "only load one version of this library and share it between all places this JS is included in this app. http://qt-project.org/doc/qt-4.8/qdeclarativejavascript.html
2) When I remove the ".pragma library" line, as the link above hints, the JS file inherits the imports of the QML file it is used from. So when I remove that line I can access i18n. This makes sense. However since the 'Clock' app, where I originally encountered this problem, uses the .pragma directive (ostensibly for performance reasons) I don't think removing it is a good solution.
3) I found the ".import" syntax for importing QML libraries into a JS file here: http://www.qt-project.org/doc/qt-5/qtqml-javascript-imports.html I might have misinterpretted it, but it looks right to me.
4) An interesting note is that when editing this code using the UbuntuSDK (QtCreator), typing "Foo." brings up "i18n" as an autocomplete suggestion. Typing "Foo.i18n." will bring up "tr()" as one of the autocomplete suggestions. So it seems like the UbuntuSDK recognizes my "Foo" Qualifier/namespace. Or maybe the autocomplete doesn't take imported libraries into account. Just thought it was interesting.
So my question is: does anyone know what's causing this behavior? I can probably work around the problem by calling i18n.tr() from a QML file rather than a JS util library, but I'm curious to know what I did wrong. Any suggestions?