【问题标题】:Using setAttribute() on an Aurelia custom attribute在 Aurelia 自定义属性上使用 setAttribute()
【发布时间】:2017-08-23 00:30:23
【问题描述】:

是否可以在 Aurelia 中使用带有自定义属性的 vanilla js setAttribute()?当我检查 dom 时,对自定义元素进行了更改,但无论我尝试什么,它似乎都不会触发我的模型或视图中的任何内容。是否有“最佳实践”方式来做到这一点?

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);
    }
}

现在加载-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>

【问题讨论】:

  • 您尝试使用 setAttribute() 吗?怎么样?
  • @YoungKyunJin 是的,当我检查 dom 时,对自定义元素进行了更改,但无论我尝试什么,它似乎都不会触发我的模型或视图中的任何内容。跨度>
  • 我可以看到你的代码吗?
  • @YoungKyunJin - 我用我的代码更新了这个问题。 colorChanged 在页面加载时触发一次,但不再触发。按下按钮后,当我检查浏览器中的元素时,color="green"colorChanged 永远不会触发。

标签: javascript aurelia


【解决方案1】:

不,Aurelia 目前似乎不支持绑定到自定义属性。

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

【讨论】:

  • 感谢您的回复。我的问题不是绑定到自定义属性。这是关于响应通过setAttribute 从元素内部更改的属性,根据该链接,该属性应该可以工作。请参阅您发布的链接中倒数第二个回复。
  • 我认为您误解了我给您的链接中的回复。在该示例中,他手动更新元素属性以反映属性更改。您正在寻找的恰恰相反,您希望模型值在属性更改时更新,这目前在 Aurelia 中是不可能的。 Dom属性和Node属性有区别,见:stackoverflow.com/questions/6003819/…
【解决方案2】:

最简单的方法是使用数据绑定。使用color.bind 而不是设置属性。如果您明确设置属性值,那么在我看来,您并没有充分利用 Aurelia。

这是你可以做的。

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

然后在数据绑定中使用color

<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>

希望这会有所帮助。

【讨论】:

  • 感谢您的回复。我知道这种方法,但我特意询问是否可以使用setAttribute() 来更新组件。几乎所有的组件式框架和库都可以响应setAttribute()。我只是想知道 Aurelia 是否也这样做了。
猜你喜欢
  • 2017-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-21
  • 1970-01-01
  • 2016-06-08
  • 2016-06-10
  • 2015-09-22
相关资源
最近更新 更多