Moes Moes - 29 days ago 14
Javascript Question

debug Aurelia ViewModel similar to ko.toJson

in knockoutjs you can output the ViewModel in a nice json format for debugging

<pre data-bind="text: ko.toJSON($data, null, 2)"></pre>


if there is a way to accomplish the same in Aurelia

Answer

You could create a custom element.

Here's an example: https://gist.run?id=9eea8902521f4523ee2c

app.html

<template>
  <require from="./debug"></require>

  <input value.bind="firstName">
  <input value.bind="lastName">

  <debug></debug>
</template>

app.js

export class App {
  firstName = 'Donald';
  lastName = 'Draper';
}

debug.html

<template>
  <pre><code>${json}</code></pre>
</template>

debug.js

export class Debug {
  bindingContext = null;

  updateJson() {
    if (this.bindingContext === null) {
      this.json = 'null';
    } else if (this.bindingContext === undefined) {
      this.json = 'undefined'
    } else {
      // todo: use a stringify function that can handle circular references.
      this.json = JSON.stringify(this.bindingContext, null, 2);
    }
  }

  bind(bindingContext) {
    this.bindingContext = bindingContext;
    this.updateJson();
    this.interval = setInterval(::this.updateJson, 150);
  }

  unbind() {
    this.bindingContext = null;
    clearInterval(this.interval);
  }
}

Result

result

Comments