0
votes

I am creating an aurelia application and have recently purchased a template which is using angular.

The template has a large number of directives for jquery/js helpers for it's pages and html elements.

Having only started to learn aurelia I am not sure the correct way to port these over, here's an example

.directive('fgLine', function(){
    return {
        restrict: 'C',
        link: function(scope, element) {
            if($('.fg-line')[0]) {
                $('body').on('focus', '.form-control', function(){
                    $(this).closest('.fg-line').addClass('fg-toggled');
                })

                $('body').on('blur', '.form-control', function(){
                    var p = $(this).closest('.form-group');
                    var i = p.find('.form-control').val();

                    if (p.hasClass('fg-float')) {
                        if (i.length == 0) {
                            $(this).closest('.fg-line').removeClass('fg-toggled');
                        }
                    }
                    else {
                        $(this).closest('.fg-line').removeClass('fg-toggled');
                    }
                });
            }

        }
    }

})

The directive is targeting a css selector and adding events to it.

Should this be a custom element? Can anyone point me in the right direction on how this should look in an aurelia way?

1
A custom element would seem to be the right direction: ilikekillnerds.com/2015/10/… - R. Richards
Yeah, you can create a customElement and use the jQuery code in attached() method - Fabio Luz
thanks guys, then to consume it, do I just need to add a require pointing to the js file in my view? - Diver Dan

1 Answers

0
votes

This should do the trick, though there might be some scoping issues with this that need to get redressed.

fgLineCustomElement.js

import { inject } from 'aurelia-framework';

@inject(Element)
export class FgLineCustomElement {

    constructor(element) {
        this.element = $(element);
    }

    attached() {
        $('body').on('focus', '.form-control', function(){
            $(this).closest('.fg-line').addClass('fg-toggled');
        })

        // a more es6-ish approach
        // $('body').on('focus', '.form-control', () => {
        //     this.element.closest('.fg-line').addClass('fg-toggled');
        // });

        $('body').on('blur', '.form-control', function(){
            var p = $(this).closest('.form-group');
            var i = p.find('.form-control').val();

            if (p.hasClass('fg-float')) {
                if (i.length == 0) {
                    $(this).closest('.fg-line').removeClass('fg-toggled');
                }
            }
            else {
                $(this).closest('.fg-line').removeClass('fg-toggled');
            }
        });
    }
}

app.html

<template>
    <require from="fgLineCustomElement"></require>
    <fg-line></fg-line>
</template>