Accessing global helper functions from within controllers

What’s the best practice for defining helper functions specific to the application and needs to be uses from within more controllers, e.g. validating dialog input? But keeping within the namespace? What about this?

App = Ember.Application.create({
    ...
    validateInput: function() {
        ....
    }
});

There must be a better way …

How about a mixin?

Mixin - 4.6 - Ember API Documentation Class packages/ember-metal/lib/mixin.js:412

You could do something like:

App.MyController = Ember.Controller.extend(App.Validation, {
    ...
});

Mixins could definitely work here.

I’d also suggest taking a look at the Ember guide for dependency injection and service lookup.

var ValidationMixin = Ember.Mixin.create({
   validateInput: function() {
      return this.container.lookup('application:main').validateInput.apply(this, arguments);
   }
});

You could do something like this I suppose to work with your above example.

I would personally create a base class for my controller which all my controllers extend from that has this validateInput function.

App.BaseController = Ember.Controller.extend({
   validateInput: function() { /*..*/ }
});

App.FooController = App.BaseController.extend();
App.BarController = App.BaseController.extend();
1 Like