Search code examples
alpacajs

Send a function along with the scheme from backend in Alpacajs


I am having an API in backend to return the full json (schema and options) for a AlpacaJS form. The content-type of the response is application/json. Following is a sample response,

{
  "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"
  }
}

When I click on the Submit button, I get the following error in browser console,

Uncaught TypeError: t.call is not a function

I think the issue is that the function is considered as a string in the following section of the response.

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

Is there a way in AlpacaJS to send a javascript function from backend, or is there a way to convert the function string to a javascript function in frontend?


Solution

  • In order to get that, you should transform the stringified function to a function by doing new Function('return ' + val)(); (beware this is a form of eval and eval is evil).

    Here's a working fiddle for that. Tell me if it didn't work for you.