【发布时间】:2015-09-22 20:21:24
【问题描述】:
我只是在使用 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;
test.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] Router navigation failed, and no previous location could be restored.
当我的页面某处出现语法错误时,我通常会收到什么消息。
这里有很多我不确定的事情:
这是自定义元素的正确用途吗? 我们可以创建带有函数的自定义元素吗? 我们可以创建具有自定义属性的自定义元素,然后在其值发生变化时触发事件吗?
很抱歉没有发布完整的代码,因为我在尝试不同的东西时有很多变体。
【问题讨论】:
-
我想通了。 this.pb 指的是进度条元素。里面是 ProgressBar 类的 progressBar 对象。因此,要访问自定义元素类中的函数 this.pb.progressBar,与属性相同。
-
如果您已经回答了您的问题,您可以发布您的实际解决方案,然后将其标记为答案吗?
标签: javascript custom-attributes aurelia custom-element