从Alpacajs的后端发送一个函数和该方案

时间:2018-02-10 16:12:59

标签: alpacajs

我在后端使用API​​来返回AlpacaJS表单的完整json(架构和选项)。响应的内容类型为application/json。以下是样本回复,

{
  "options": {
    "fields": {
      "students": {
        "items": {
          "type": "tablerow"
        },
        "type": "table"
      }
    },
    "form": {
      "buttons": {
        "submit": {
          "click": "function(){alert(\"sample\");}"
        }
      }
    }
  },
  "schema": {
    "properties": {
      "students": {
        "items": {
          "properties": {
            "name": {
              "required": true,
              "title": "Name",
              "type": "string"
            },
            "contact-number": {
              "title": "Age",
              "type": "string"
            }
          },
          "type": "object"
        },
        "type": "array"
      }
    },
    "type": "object"
  }
}

当我点击Submit按钮时,我在浏览器控制台中收到以下错误

Uncaught TypeError: t.call is not a function

我认为问题是该功能在响应的以下部分被视为字符串。

"form": {
  "buttons": {
    "submit": {
      "click": "function(){alert(\"sample\");}"
    }
  }
}

AlpacaJS中是否有一种方法可以从后端发送javascript函数,或者有没有办法将函数字符串转换为前端的javascript函数?

1 个答案:

答案 0 :(得分:2)

为了实现这一点,您应该通过执行new Function('return ' + val)(); stringified 函数转换为函数(请注意这是eval和eval is evil的一种形式)。

这是一个有效的fiddle。 告诉我它是否适合你。