Any reason, why Ember does not support global functions through js file import

Any reason, why Ember expect Mixin, Service or environment App block approach to use generic functions. It would have been more seamless experience for Object Oriented JavaScript developers coming to ember to have global functions usage through import of javascript files.

Any insights of ember thought process in not allowing direct js file import to use global functions would help a lot.

2 Likes

It doesn’t. You can export a function in a new file app/foo/bar.js and then import it in any other js file, like an Ember component or just foo/xyz.js. That is a generic export and import that does not rely on anything Ember-related. It is not a global function, but I don’t think that’s what you meant.

2 Likes

There is even a useful ember-cli blueprint for it - util <name>

ie. ember g util myFunction will generate a file in app/utils/my-function.js with an empty function exported, ready for you to implement and import.

4 Likes

How to access this generated function else where… say if myFunction takes two parameters and I wish call this in application adopter

Also is it possible to put multiple functions in a single file, rather than one one function in one file…

ember g util myFunction is generating one file per a global function.

As rutinerad wrote, this is generic export that isn’t handled specially by Ember - you can export anything - string, array, object, function, etc… and it doesn’t have to be placed in the utils folder, you can place it anywhere.

Simply change the code to export an object with multiple functions:

export default {
	fu() {
		Ember.Logger.info('fu!');
	},
	add(a,b) {
		Ember.Logger.info('added: ', a+b);
	}
}

regarding the 1st question, you need to import this file to where you need it - eg.

import myFunctions from '../../utils/my-functions';

myFunctions.add(4,5);

or alternatively:

import {add} from '../../utils/my-functions;

add(6,7);
2 Likes

I apologize for necroposting. Have you tried to run your code? The last option doesn’t seem to work:

import {add} from '../../utils/my-functions;

add(6,7);

Console output:

Uncaught TypeError: (0 , _myFunctions.add) is not a function

That’s cause the code sample isn’t using a named export.

Change to exporn function add(...

And you can import using your app name instead of relative directory parental traversing, app-name/utils/my-util-file.js

1 Like

Already solved, but thanks anyway bruh

1 Like