简体   繁体   中英

Using setAttribute() on an Aurelia custom attribute

Is it possible in Aurelia to use vanilla js setAttribute() with custom attributes? When I inspect the dom, the change is made on the custom element, but it doesn't seem to trigger anything in my model or view no matter what I try. Is there a "best practice" way to do this?

home.ts

export class Home{
    public onButtonClicked():void{
        document.getElementById('test123').setAttribute('color', 'green');
    }
}

home.html

<template>
    <require from="../../elements/now-loading-circle/now-loading-circle"></require>
    <button click.delegate="onButtonClicked()">Click</button>
    <now-loading-circle id="test123" color="red"></now-loading-circle>
</template>

now-loading-circle.ts

import {bindable, autoinject} from 'aurelia-framework';
@autoinject
export class NowLoadingCircle{
    @bindable color:string;
    public colorChanged(newValue):void{
        alert(newValue);
    }
}

now-loading-circle.html

<template>
    <svg viewBox="0 0 120 120">
        <circle repeat.for="circ of coords" cx="${circ.x}" cy="${circ.y}" r="${smallCircleRadius}" class="circ-${$index + 1}"></circle>
    </svg>
</template>

The simplest way to do this is to use data-binding. Use color.bind instead of setting the attribute. If you set the attribute value explicitly, then in my opinion you are not leveraging Aurelia to its full extent.

This is what you can do.

export class Home{
    color: string; // have a member in Home.
    public onButtonClicked():void{
        this.color = 'green';
    }
}

And then use the color in data-binding:

<template>
    <require from="../../elements/now-loading-circle/now-loading-circle"></require>
    <button click.delegate="onButtonClicked()">Click</button>
    <now-loading-circle id="test123" color.bind="color"></now-loading-circle>
</template>

Hope this helps.

No, Aurelia currently does not seem to support binding to custom attributes.

https://github.com/aurelia/binding/issues/380

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