Custom attribute in aurelia no working?

2019-06-23 05:02发布

问题:

I am learning how Aurelia works and I am trying to get a simple custom attribute working. All it will do is change the color of a div text depending on some value changing.

I have a div which has:

    high.bind="changeColor"

and in my attribute I have :

import {inject, customAttribute} from 'aurelia-framework';

@customAttribute('high')
@inject(Element)
export class High {
    constructor(element) {
       this.element = element;
   }

   valueChanged(newValue){
   console.log(newValue);
   if (newValue) {
     this.element.classList.remove('highlight-yellow');
   } else {
     this.element.classList.add('highlight-blue');
  }
}

In my view model I have :

import {high} from './highlightattribute'


export class Welcome{
  heading = 'Welcome to the Aurelia Navigation App!';
  firstName = 'John';
  lastName = 'Doe';

 get fullName(){
   return `${this.firstName} ${this.lastName}`;
 }

 get changeColor(){
  if (this.firstName == 'John'){
    return false;  
  }
  return true;
 }  
 welcome(){
   alert(`Welcome, ${this.fullName}!`);
 }
}

When I change the firstname I do not see the valueChanged event being triggered in the high custom attribute class.

回答1:

It looks like you are importing the high code in to your viewmodel rather than your view. Remove this line in your ViewModel:

import {high} from './highlightattribute'

Then and add this line to your View:

<require from="./highlightattribute"></require>

Next, in the highlightattribute.js file you are removing highlight-yellow and adding highlight-blue, so you will probably want to add and remove the same class. I did also notice that there is a missing parenthesis in your highlightattribute.js file you posted, but that was probably just missed while copying the code.

Let me know if this helps solve the problems. I have pushed a sample with your code to here: https://github.com/AshleyGrant/skeleton-navigation/tree/so-answer-20150416-01/src



标签: aurelia