Accessing Custom Component Data/methods
Solution 1:
There's an explanation for that in the documentation.
The General Rule for Aurelia's DI Use
Everything is an application-level singleton except for those things which are classified as "components", essentially custom elements, custom attributes and view-models created through the router or composition engine. You can change the lifetime of router and composition created components through explicit configuration.
I'd recommend using EventAggregator instead of injection. This approach ensures flexibility, extensibility and prevents tight-coupling as well.
About EventAggregator: #1 Walkthrough by Dwayne Charrington, Documentation, Contact Manager Tutorial.
Here's a gist to demonstrate it with your scenario: https://gist.run/?id=f66eaa12e4183a72a7a3cc01ce3a8fb5
app.js
Let's assume that we'd like to use more than one instances of Component
custom component. To achieve that, we can publish a component:save
event with associated data.
import { inject } from"aurelia-framework";
import { EventAggregator } from'aurelia-event-aggregator';
@inject(EventAggregator)
exportclassApp {
components = [
{ id: 1, name: 'Component #' },
{ id: 2, name: 'Component #' },
{ id: 3, name: 'Component #' }
];
constructor(eventAggregator) {
this.eventAggregator = eventAggregator;
}
SubmitData(opts) {
this.eventAggregator.publish('component:save', opts);
}
// ...
}
component.js
Here we can subscribe to component:save
events and check if we should proceed with saving. For this reason, each Component
instances should have a unique identification (number, hash, uid, etc..).
Note: there's an important cleanup part in detached
method, which isn't mentioned explicitly in official documentation. That's why I've listed Dwayne Charrington's blog post first.
import { inject, bindable } from 'aurelia-framework';
import { EventAggregator } from 'aurelia-event-aggregator';
@inject(EventAggregator)
export classComponent{
@bindable
id;
object = {};
constructor(eventAggregator) {
this.eventAggregator = eventAggregator;
}
bind() {
this.object = {
"Name": `My name ${this.id}`,
"Age": 21
};
console.log(`component ADDED: #${this.id}`);
this.subscriber = this.eventAggregator.subscribe('component:save', data => {
if (data.id === this.id || data.all === true) {
this.SubmitObjectToDatabase();
console.log(`component:save SAVED: #${this.id}`, this.object.Name);
} else {
console.log(`component:save PASSED: #${this.id}`);
}
});
}
SubmitObjectToDatabase() {
console.log(`SubmitObjectToDatabase has been called: #${this.id}`);
}
detached() {
// cleanupthis.subscriber.dispose();
console.log(`component REMOVED: #${this.id}`);
}
}
Post a Comment for "Accessing Custom Component Data/methods"