Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aurelia observable with object property

I'm trying to set a watch on when an object property changes in Aurelia. I haven't used observables before so please help me. Based on the documentation, here's what I think would work, but I suspect the dot is throwing off the function name or observable.

export class EventEdit {
  record = {
    ev_date_start,
    ev_date_end,
    ev_description
  };
  @observable record.ev_date_start;

  record.ev_date_startChanged(newValue, oldValue) {
    console.log("ev_date_start changed from " + oldValue + " to " + newValue);
  }
}

Nothing happens when I change the value of ev_date_start.

like image 609
LStarky Avatar asked Nov 30 '16 17:11

LStarky


1 Answers

It's better to define a class when you need a complex object.

import { observable } from 'aurelia-framework';

export class EventEdit {
  constructor() {
    this.model = new EventModel();

    setTimeout(() => {
      this.model.ev_date_start = "test";
    }, 2000);
  }
}

export class EventModel  {
    @observable ev_date_start;
    ev_date_end;
    ev_description;

    ev_date_startChanged(newValue, oldValue) {
      console.log("ev_date_start changed from " + oldValue + " to " + newValue);
    }
}

Another solution is using the BindingEngine:

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

@inject(BindingEngine)
export class EventEdit {
  record = {
    ev_date_start,
    ev_date_end,
    ev_description
  };

  constructor(bindingEngine) {
    this.bindingEngine = bindingEngine;
  }

  attached() {
    this.subs = this.bindingEngine
       .propertyObserver(this.record, 'ev_date_start')
       .subscribe(this.ev_date_startChanged);
  }

  detached() {
    this.subs.dispose();
  }

  ev_date_startChanged(newValue, oldValue) {
    console.log("ev_date_start changed from " + oldValue + " to " + newValue);
  }
}
like image 72
Fabio Luz Avatar answered Oct 03 '22 08:10

Fabio Luz