0

我想在方法中增加一个计数器,如下所示:

  row(title, height):: {
    _panels:: [],
    _panelSlot:: 0,

    addPanel(panel):: self {
      self._panelSlot = self._panelSlot + 1,
      _panels+: [{
          slot: panelSlot,
          panel: panel,
      }],
    },

该行self._panelSlot = self._panelSlot +1是我期望的工作,但这确实会导致以下错误:

STATIC ERROR: lib/grafana/builder.libsonnet:157:7-11: unexpected: self while parsing field definition

我的第二次尝试:

我不确定这是否会覆盖该_panelSlot变量,但我无法确认,因为我无法访问我的对象数组上的该变量:

  row(title, height):: {
    _panels:: [],
    // height is the row's height in grid numbers and it is used' to calculate the 
    // panel's height and y pos accordingly.
    _height:: height,
    // panelSlot is the row panels' current position from left-to-right. If there are
    // two or more stacked panels they share the same slot. This is used to calculate
    // the width for each panel.
    _panelSlot:: 0,

    addPanel(panel):: self {
      local parent = self,
      _panelSlot:: self._panelSlot + 1,
      _panels+: [{
          slot: parent._panelSlot,
          panel: panel,
      }],
    },
RUNTIME ERROR: max stack frames exceeded.
...
<anonymous>
        lib/grafana/builder.libsonnet:(13:9)-(15:10)    thunk <array_element>
        lib/grafana/builder.libsonnet:19:29-35  object <anonymous>
        lib/grafana/builder.libsonnet:19:15-37  thunk <array_element>
        lib/grafana/builder.libsonnet:(7:24)-(20:6)     object <anonymous>
        During manifestation

我的问题

如何修改方法中的变量(即递增计数器),以便在下次调用该方法时可以访问修改后的变量?

4

1 回答 1

0

如何修改方法中的变量(即递增计数器),以便在下次调用该方法时可以访问修改后的变量?

IIUC 你不能像其他 OOP 语言那样真正保持和改变状态

您可以通过链接返回新对象的调用将一个对象变为一个对象(使用修改/添加的数据)来解决此问题

示例 1

在下面制作一个示例:

代码:

local Array = {
  array: [],
  count: 0,

  addElem(e):: self {
    // Overload (mutate) this object
    array+: [e],
    count+: 1,
  },  // return mutated object
};

// Below 4 lines are equal to
// Array.addElem('x').addElem('y').addElem('z'); but kinda more readable
local obj = Array
            .addElem('x')
            .addElem('y')
            .addElem('z');

obj

输出:

$ jsonnet example1.jsonnet
{
   "array": [
      "x",
      "y",
      "z"
   ],
   "count": 3
}

示例 2

将上述方法应用于您的代码:

代码:

local Class = {

  Row(title, height):: {
    local this = self,  // clamp a reference to the current self

    _panelSlot: 0,
    _panels: [],
    _height: height,

    title: title,

    // addPanel() changes it-`self` to return a mutated Row
    addPanel(panel):: self {
      _panelSlot+: 1,
      _panels+: [{
        slot: this._panelSlot,
        panel: panel,
      }],
    },
  },
};

local obj = Class
            .Row('Title', 42)
            .addPanel('Foo')
            .addPanel('Bar');

obj

输出:

$ jsonnet example2.jsonnet
{
   "_height": 42,
   "_panelSlot": 2,
   "_panels": [
      {
         "panel": "Foo",
         "slot": 0
      },
      {
         "panel": "Bar",
         "slot": 1
      }
   ],
   "title": "Title"
}

顺便说一句,如果你还没有的话,建议你看看grafonnet-lib 。

于 2021-07-19T15:38:28.290 回答