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


#1

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

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.


#3

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

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.


#5

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);