简体   繁体   中英

Add new JS class and template to aurelia project

I am new to Aurelia, but am working on an existing project and learning as I go. I want to add a javascript class file and have NPM include it in the build, but I cannot find clear documentation on how to do that.

It is not a complex class and does not require an html template.

只需将包含类的.js文件添加到src文件夹中,然后添加以下内容以将其导入您打算使用该类的文件中即可。

import * as MyClass from './my-classs';

following the convention, you can create a class with the below...

export class MyClass {
    myProperty = 'foo';
    myOtherProperty = { key:'value' };

    constructor() {
        // constructor stuff (optional of course)
    }

    myMethod() {
        // do something
    }
}

Then in your ViewModel, for example...

import { inject } from 'aurelia-framework';
import { MyClass } from 'path/to/my-class';

@inject(MyClass)
export class MyViewModel {
    constructor(myClass){
        this.myClass = myClass;
    }

    attached() {
        console.log(this.myClass.myProperty);
        this.myClass.myMethod();
    }
}

The way you import your class does depend on whether it's written as a module or not. If it's not a module, you'll have to write it out as @john-little mentioned.

The MyClass will automatically be a singleton until you make it transient (see https://aurelia.io/docs/fundamentals/dependency-injection#object-lifetime-child-containers-and-default-behavior )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM