Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aurelia - Invoke "Refresh" on child component

I am looking at adding a "refresh" button to a screen that has a few Aurelia components. I'd rather not build this into the component that is the target of the refresh.

So basically I'd like to repull some web data to update the component when this "refresh" button is clicked. "Reinitializing" the component such that the constructor would run again would also be acceptable. I'd apply this same concept to several components I have, if a pattern exists for solving this generically that would be exquisite.

I envisioned a solution to this involving somehow invoking a method on the child component that I could add e.g. something like childcomponent.Refresh(). However, I'm not sure how I would reference the child component.

What is an appropriate way to handle this situation?

like image 787
Joshua Enfield Avatar asked Feb 12 '16 18:02

Joshua Enfield


1 Answers

many ways to do this, here's a couple of options:

With Data-Binding:

app.html

<template>
  <button click.delegate="refresh()">Refresh</button>
  <component1 data.bind="myData"></component1>
  <component2 data.bind="myData"></component2>
  <component3 data.bind="myData"></component3>
</template>

app.js

export class App {
  myData = null;

  activate() {
    return this.refresh();
  }

  refresh() {
    someService.loadData() 
      .then(data => this.myData = data);
  }
}

component1.js

import {bindable} from 'aurelia-framework';

export class Component1 {
  @bindable data;

  dataChanged(newValue, oldValue) {
    // do something when the data changes...
  }
}

With the EventAggregator:

app.html

<template>
  <button click.delegate="refresh()">Refresh</button>
  <component1></component1>
  <component2></component2>
  <component3></component3>
</template>

app.js

import {inject} from 'aurelia-framework';
import {EventAggregator} from 'aurelia-event-aggregator'; // jspm install aurelia-event-aggregator

@inject(EventAggregator)
export class App {
  constructor(eventAggregator) {
    this.eventAggregator = eventAggregator;
  }

  activate() {
    this.refresh();
  }

  refresh() {
    someService.loadData() 
      .then(data => this.eventAggregator.publish('data changed', data);
  }
}

component1.js

import {inject} from 'aurelia-framework';
import {EventAggregator} from 'aurelia-event-aggregator'; // jspm install aurelia-event-aggregator

@inject(EventAggregator)
export class Component1 { 
  constructor(eventAggregator) {
    this.eventAggregator = eventAggregator;
  }

  dataChanged(data) {
    // do something when the data changes...
  }

  bind() {
    this.subscription = this.eventAggregator.subscribe('data changed', data => this.dataChanged(data));
  }

  unbind() {
    this.subscription.dispose();
  }
}
like image 195
Jeremy Danyow Avatar answered Oct 20 '22 21:10

Jeremy Danyow