调试Aurelia ViewModel类似于ko.toJson

Moe*_*oes 10 javascript aurelia aurelia-binding

在knockoutjs中,您可以输出一个漂亮的json格式的ViewModel进行调试

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

如果有办法在Aurelia完成同样的事情

Jer*_*yow 15

您可以创建自定义元素.

这是一个例子:https://gist.run?id = 9eea8902521f4523ee2c

app.html

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

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

  <debug></debug>
</template>
Run Code Online (Sandbox Code Playgroud)

app.js

export class App {
  firstName = 'Donald';
  lastName = 'Draper';
}
Run Code Online (Sandbox Code Playgroud)

debug.html

<template>
  <pre><code>${json}</code></pre>
</template>
Run Code Online (Sandbox Code Playgroud)

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

结果

结果

  • 问题是,在aurelia中,您通常会将一些aurelia对象(例如router或eventaggregator)注入并附加到viewmodel.然后你得到a)循环引用错误,或b)你的转储被许多大的aurelia对象"污染".我想要一种只转储viewModel的'my'属性的方法.有任何想法吗? (2认同)