简体   繁体   中英

Template vs Class in Aurelia

Consider the following example, and please note the setActive function in app-bar.js .

Now as it stands, if I click Home or Plan from app-bar.html , the activeTab property in app.js is updated appropriately. However, if I click the middle button, which invokes the aforementioned function, I receive the following error: Uncaught ReferenceError: activeTab is not defined . Moreover, if I change the setter to this.activeTab = newTab , no error is thrown, yet the value is not bound back to activeTab in app.js

What is going on here? Why is the DOM template the only piece of my component that's able to see/interact with activeTab ? Am I missing necessary syntax in my class? If so, please provide documentation.

I was banging my head on my desk for a while, and on a whim I deciced to put activeTab = 'Home' on the click.trigger itself, and it magically works, yet I have no understanding why. I do not like the idea of updating model values in template, so I'd like to pass the event to JS and have that update the model, but as we can see, it doesn't work.

Let me know if you need any additional information.

app.js

export class App {
    activeTab = 'Home';
}

app.html

<template>
    <require from="app-bar"></require>
    <h4>ActiveTab via App.js: ${activeTab}</h4>
    <app-bar></app-bar>
</template>

app-bar.js

export class AppBar {
    setActiveTab(newTab) {
        activeTab = newTab;
    }
}

app-bar.html

<template>
  <button click.trigger="activeTab = 'Home'">Home</button>
  <button click.trigger="setActiveTab('Assess')">Assess</button>
  <button click.trigger="activeTab = 'Plan'">Plan</button>
</template>

在此处输入图片说明

The problem is here:

export class AppBar {
    setActiveTab(newTab) {
        activeTab = newTab; // <---- what is `activeTab`?  It's not defined anywhere!
    }
}

You probably want to do something like this:

app-bar.js

import {bindable, bindingMode} from 'aurelia-framework';

export class AppBar {
    @bindable({ defaultBindingMode: bindingMode.twoWay }) activeTab;

    setActiveTab(newTab) {
        this.activeTab = newTab;
    }
}

app.html

<template>
    <require from="app-bar"></require>
    <h4>ActiveTab via App.js: ${activeTab}</h4>
    <app-bar active-tab.bind="activeTab"></app-bar>
</template>

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