2

I have the following code, but when the onChange is triggered it gives me an error. (Uncaught TypeError: Cannot set property 'myVar' of undefined)

import { inject } from 'aurelia-framework';
import { ObserverLocator } from 'aurelia-framework';

@inject(ObserverLocator)
export class myClass{
    field= "";
    myVar = 0;
    constructor(observerLocator) {
        this.field= "";
        var subscription = observerLocator
                .getObserver(this, 'field')
                .subscribe(this.onChange);

    }

    onChange(){
        this.myVar +=1;
    }

}
abc
  • 25
  • 4
  • Remove `this` from `this.myVar = 0;` then it should work – kabaehr Apr 20 '16 at 10:52
  • Thank you for your response. Sorry I did a mistake when i created the demonstration code. I get this error(Uncaught TypeError: Cannot set property 'myVar' of undefined) when i change the value of field. – abc Apr 20 '16 at 11:42
  • Try to use the BindingEngine instead http://stackoverflow.com/questions/28419242/property-change-subscription-with-aurelia – Fabio Apr 20 '16 at 13:16

1 Answers1

1

It's scope issue, just try

var subscription = observerLocator
            .getObserver(this, 'field')
            .subscribe(this.onChange.bind(this));
valichek
  • 1,186
  • 6
  • 9