2

I'm trying to generate JSON for display clickable Konva object. All attributes working as expected except onClick.

How to pass a JS function in JSON with Laravel Respons::json()?

Here's what I've tried.

return Response::json([
            'status' => 'completed',
            'message' => 'Question ID:'.$id.' Retreived',
            'data' => [
                
                    "attrs" => [
                        "width" => 1200,
                        "height"=> 200
                    ],
                    "className" => "Stage",
                    "children" => [
                        [
                            "attrs"=>[],
                            "className"=>"Layer",
                            "children"=>[
                                [
                                    "attrs"=>[
                                        "x"=>125,
                                        "y"=>100,
                                        "text"=>"Test Text",
                                        "onClick"=> "{() => console.log(test)}",
                                        "fontSize"=>25,
                                    ],
                                    "className"=>"Text"
                                ]
                            ]
                        ],
                    ]
                
            ]
        ], 200);

but I got this error

TypeError: selfListeners[i].handler.call is not a function. (In 'selfListeners[i].handler.call(this, evt)', 'selfListeners[i].handler.call' is undefined)

  • I think it is client side (React) error. JSON response seems ok. Check your response in API client tool, such as postman. If everything is allright, you should update your React code. – Nazem Mahmud Piash Jul 04 '21 at 15:10

1 Answers1

3

Konva is not using JSON data to attach events. JSON is used only for attributes. So such onClick event will be not attached. It will be just added as onClick attribute, which is not what you want.

And in general, I am not sure if it is a good idea to save/load events and js function inside JSON object. JSON should be used just for attributes and state of your application.

lavrton
  • 18,973
  • 4
  • 30
  • 63