Trondh
Trondh

Reputation: 3341

Organizing global functions in aurelia

I have a function that I'd like to use in several of my ViewModels. It's a filter function that I use as a param for a custom filter:

<tr repeat.for="server of servers | filter:searchTerm:filterFunc">

What is the "aurelic" way of storing functions like this? I'm very new to both js and aurelia, so an easy-to-understand "non-minified" example would make me super-grateful :-)

EDIT: For reference, I stuck the function inside my ValueConverter class since it will only be used in conjunction with it.

export class filterValueConverter {
   myCustomFunc(stuf,stuf){}
   toView(array, searchTerm){return this.myCustomFunc}}

Upvotes: 2

Views: 1281

Answers (1)

Erik Lieben
Erik Lieben

Reputation: 1247

You would probably need to create a value converter for an array to do this.

Html in view(s):

<div repeat.for="item of [1, null, 2] | notNullFilter">${item}</div>

Filter (src\resources\value-converters\notNullFilterValueConverter.js):

export class notNullFilterValueConverter {  
  toView(array) {
    return array.filter(item => item !== null);
  }
}

And register it as global resource in your main.js setup:

import {Aurelia} from 'aurelia-framework';

export function configure(aurelia: Aurelia) {
  aurelia.use
    .standardConfiguration()
    .developmentLogging()
    .globalResources([ 
      "./src/resources/value-converters/notNullFilterValueConverter"
    ]);

  aurelia.start().then(() => aurelia.setRoot());
}

You can just insert any number of value converters in the array you give to the global resources function.

Which will output

<div>1</div>
<div>2</div>

If at some stage this becomes clouded/ messy, you could move it to a feature:

export function configure(aurelia: Aurelia) {
        aurelia.use
            .standardConfiguration()
            .developmentLogging()
            .feature('resources'); 

        aurelia.start().then(function () { return aurelia.setRoot('views/app'); });
}

Add a folder named 'resources' with a file inside index.js

export function configure(config) {
  config.globalResources('./notNullFilterValueConverter', './welcomeValueConverter');
}

A 'feature' is the same as a plugin with the only difference that it is living in your source tree. It allows you to make multiple features, so there could be for example one called company-array-filters and one custom-company-elements.

Upvotes: 4

Related Questions