我只是在玩弄 Aurelia 中的自定义元素功能,并尝试创建一个“进度条”元素。
进度条.js
import {customElement, bindable} from 'aurelia-framework';
@customElement('progress-bar')
export class ProgressBar
{
//do stuff//
}
进度条.html
<template>
<link rel="stylesheet" type="text/css" href="src/components/progress-bar.css">
<div class='progress-bar' tabindex=0 ref="bar">bloo</div>
</template>
test.html(相关部分)
<require from="./components/progress-bar"></require>
<progress-bar ref="pb">a</progress-bar>
所有这一切都很好。但我正在努力研究如何让主页可以调用某些函数或更改元素上的某些属性,然后应该在进度条本身上做一些事情。
我试图在 progress-bar.js 中创建一个函数“doSomething”,但我无法在 test.js 中访问它。
添加到 progress-bar.js
doSomething(percent, value) {
$(this.bar).animate('width: ${percent}%', speed);
}
在 test.js 中
clicked() {
console.log(this.pb); // this returns the progress bar element fine
console.log(this.pb.doSomething); //this returns as undefined
this.pb.doSomething(percent, value); // this fails outright with error: typeError - doSomething is not a function
}
接下来,我尝试在进度条元素内设置自定义属性,并可能使用 valueChange 来更改 div。
内部 progress-bar.js
@bindable percent=null;
@bindable speed=null;
测试.js
clicked() {
this.pb.percent=50; //this updated fine
this.pb.speed=1500; //this updated fine
}
没问题,差不多了。 但是,如何设置一个处理程序以在属性更改时调用?
我找到了一个语法如下的教程:
@bindable({
name:'myProperty', //name of the property on the class
attribute:'my-property', //name of the attribute in HTML
changeHandler:'myPropertyChanged', //name of the method to invoke on property changes
defaultBindingMode: ONE_WAY, //default binding mode used with the .bind command
defaultValue: undefined //default value of the property, if not bound or set in HTML
})
但我似乎无法在我的 progress-bar.js 中使用该代码。 添加后页面无法正确呈现。Gulp 似乎没有返回任何错误消息,但浏览器控制台返回此错误:
ERROR [app-router] 路由器导航失败,无法恢复之前的位置。
这是我在页面某处出现语法错误时通常收到的消息。
这里有很多我不确定的事情:
这是对自定义元素的正确使用吗? 我们可以创建带有功能的自定义元素吗? 我们能否创建具有自定义属性的自定义元素,然后在其值更改时触发事件?
很抱歉没有发布完整的代码,因为我在尝试不同的东西时有很多变体。
最佳答案
使用 Aurelia,您可以在组件中使用此约定:yourpropertynameChanged()
import {customElement, bindable, inject} from 'aurelia-framework';
import $ from 'jquery';
@customElement('progress-bar')
@inject(Element)
export class ProgressBar
{
@bindable percent;
@bindable speed;
constructor(element){
this.element = element;
}
percentChanged(){
doSomething(this.percent, this.speed);
}
speedChanged(){
doSomething(this.percent, this.speed);
}
doSomething(percent, value) {
$(this.element).animate('width: ${percent}%', value);
}
}
您不需要从外部访问 doSomething()
。
但是你只需要改变属性:
<progress-bar percent="${pb.percent}" speed="${pb.speed}">a</progress-bar>
关于javascript - Aurelia:访问自定义元素的自定义函数或自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31233113/