Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 391
Nerdroid Avatar asked Sep 03 '15 02:09

Nerdroid


2 Answers

The closest I've got is to define a Value Converter. So in json.js I have

export class JsonValueConverter {
    toView(value) {
        return JSON.stringify(value, null, "\t");
    }
}

then in my view-model index.js I have my data:

export class IndexViewModel {
    data = {
        name: "nobody!"
    };
}

and finally the view index.hml binds and uses the converter:

<template>
    <require from="../resources/converters/json"></require>
    <pre textContent.bind="customElementModel | json"></pre>
</template>

However, I'm stumped at the moment by the lack of live binding between the model and the HTML so this may not fully answer your question?

like image 151
Phil Avatar answered Oct 05 '22 23:10

Phil


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

like image 21
Jeremy Danyow Avatar answered Oct 06 '22 00:10

Jeremy Danyow