Monitor when a button in a grapesjs modal is clicked

When using the Grapesjs Editor, I needed a modal with a form inside it. Upon clicking the submit button, I wanted to trigger a Function that would make an ajax call.

To achieve this, I attempted to create a custom component by extending it from the default component and then loading it as a block. While I was successful in getting the modal with the form to display, I faced difficulties in tracking the form submit button event.

Here is a snippet of my code:

 const domc = editor.DomComponents;
  const defaultType = domc.getType('default');
  const defaultModel = defaultType.model;
  const defaultView = defaultType.view;

  domc.addType("test-type", {
    model: defaultModel.extend(
      {
        defaults: Object.assign({}, defaultModel.prototype.defaults, {
          type      : "test-type",
          id:"popup",
          droppable : false,
          resizable : true,
          tagName:"popup",
        }),
        getAttrToHTML: function() {
          var attr = defaultType.model.prototype.getAttrToHTML.apply(this, arguments);
          delete attr.onmousedown;
          var testmarker = this.get("testmarker");
          if(testmarker)
            attr.testmarker = testmarker;
            console.log(attr)
          return attr;
        }
      }),
    view: defaultType.view.extend({
      tagName: "button",
      events: {
        "dblclick": "openModal",
      },
      initialize: function(o) {
        defaultType.view.prototype.initialize.apply(this, arguments);
        this.listenTo(this.model, "change:testmarker", this.updateMarker);
        this.listenTo(this.model, "dblclick active", this.openModal);
      },

      updateMarker: function() {
        var testmarker = this.model.get("testmarker");
        console.log(this.$el.byId)
        console.log(this.$el._events);
        this.$el.attr("testmarker", testmarker);
      },

      openModal: function(e) {

        const modal = editor.Modal;
        console.log(modal)
        modal.open({
          title: '<br>Create Identity<br>',
          content: `
          <div class="container"> 
              <form onsubmit="formSubmit()">
              <div class="form-group">
              <label>URL</label>
               <input type="text" class="form-control" id="url" placeholder="http://test-data/" name="url">
              </div>
              <div class="form-group">
              <label>Identity </label>
               <input type="text" class="form-control" id="address" placeholder="Enter Identity Address" name="address">
              </div>
              <button type="submit" class="btn btn-danger">Submit</button>
              </form>
              </div>`,

        });

Answer №1

It is important to ensure that your JavaScript logic, such as listening for clicks and making AJAX calls, is defined within the script section of your custom component definition. For more information, you can refer to this helpful resource: components and js

UPDATE: If you are determined to use this approach within the view section, you can follow these steps:

view: defaultType.view.extend({
    events: {
        click: 'handleClick',
    },
    createContent() {
        const content = document.createElement('div');
        content.style = 'position: relative';
        content.innerHTML = `
                <div class="container"> 
                  <form>
                      <div>
                          <label>URL: </label>
                           <input type="text" id="url" placeholder="http://test-data/" name="url">
                      </div>
                      <div>
                          <label>Identity: </label>
                           <input type="text" id="address" placeholder="Enter Identity Address" name="address">
                      </div>
                  </form>
                </div>
    <button style="
      position: absolute;
      top: 0; right: 0;
      background-color: #fff;
      font-size: 1rem;
      border-radius: 3px;
      border: none;
      padding: 10px 20px;
      cursor: pointer
    ">
         Submit
    </botton>
  `;

        return content;
    },
    handleClick: function (e) {
        var modal = editor.Modal;
        var content = this.createContent()
        var btn = content.children.length === 2 && content.children[1];
        btn.addEventListener('click', this.applyChanges)
        modal.open({
            title: '<br>Create Identity<br>',
            content: content
            ,
        });
    },
    applyChanges() {
      // ADD YOUR AJAX FUNCTIONALITY HERE
    },
}),

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is Apache required for running NodeJs?

Recently, I set up a web project on my local machine following a tutorial. With the help of XAMPP, I was able to install MySQL and Apache to run my Node.JS backend. Now, I'm looking into hosting the project on an external server to make it accessible ...

In VueJS, where specifically do you typically look to catch emitted events?

Let's set the stage: export default Vue.extend({ name: 'Home', computed: { ...mapState('user', ['card']), }, created() { this.fetchData(); }, mounted() { this.$once('dataLoaded', () => { if ...

Discover the steps to retrieve a fresh array in PHP after utilizing sortable.js

Hi there! I am currently utilizing the sortable javascript feature found on Although the script is working perfectly fine for me, being a non-expert in javascript poses a challenge when it comes to generating the necessary code to retrieve an array in php ...

Error encountered in Vue3: An uncaught TypeError occurred when attempting to "set" a property called 'NewTodo' on a proxy object, as the trap function returned a falsish

I encountered an error message: Uncaught TypeError: 'set' on proxy: trap returned falsish for property 'NewTodo' This error occurs when attempting to reset the input text value within a child component (FormAddTodo.vue). App.vue: expo ...

Using Vue.js for redirecting with a post method

Is there a way to redirect from Vue.js to a Laravel controller using the POST method without using AJAX? I would like to be able to use var_dump or dd inside the controller. //Vue.js axios.post('/add-hotel-listing', this.finish).then((respons ...

Delete a particular item from a JSON object in real-time using TypeScript/JavaScript

Upon examining the JSON data provided, it contains a node called careerLevels which includes inner child elements. input = { "careerLevelGroups": [ { "201801": 58, "201802": 74, ...

How can we parse the returned 'data' as HTML in JavaScript/jQuery to select more elements?

After receiving data from a webservice, it turns out that the data is just raw HTML without any XML headers or tags around it, but simply a piece of HTML code. <div class="Workorders"> <div id="woo_9142" class="Workorder"> <span ...

looking to implement auto-scroll feature in flatlist using react native

I'm attempting to implement auto-scroll functionality in my FlatList, but I'm encountering a problem where the list does not scroll automatically. Additionally, whenever I try to manually scroll, it reverts back to index 0 every 5 seconds. Below ...

NodeJS allows for seamless uploading of files

I'm encountering difficulties when trying to upload a file using nodeJS and Angular. I've come across some solutions, but they all involve Ajax which is unfamiliar territory for me. Is there a way to achieve this without using Ajax? Whenever I ...

Creating directional light shadows in Three.JS: A Step-by-Step Guide

Can shadows be generated using a DirectionalLight? When I utilize SpotLight, shadows are visible. However, when I switch to DirectionalLight, the shadow functionality doesn't seem to work. ...

Leveraging a specialized Angular filter as a cellFilter within the columnDefs of ui-grid, set in an Angular constant

In my Angular application called myApp, I have a unique filter named myFilter. Additionally, I am utilizing UI Grid to display data in multiple grids such as myGrid1 and myGrid2. To streamline the process, I have organized column definitions for these grid ...

One file successfully imports a dependency, while the other file does not seem to recognize it

I'm diving into the world of Vuex, exploring how to create an auth module. I came across some examples that I'm trying to implement, but I've hit a roadblock when attempting to use axios in my store. My store is structured with separate file ...

Issue with highlighting when one string overlaps with another

I am facing a challenge with handling a string that contains Lorem Ipsum text. I have JSON data that specifies the start and end offsets of certain sections within the text that I need to highlight. The approach I am currently using involves sorting the JS ...

Develop a custom BuyMeACoffee feature for Gatsby JS

I am currently working on developing a Buy Me A Coffee React component to include in my Gatsby website. Despite successfully running and building my Gatsby site in development mode, I am encountering an issue where the Buy Me A Coffee widget does not displ ...

I'm having trouble getting my application to output to the console. What could be the issue?

In my cr-route.js file, I have a function that ensures the user is authenticated before displaying their name. module.exports = function (app, passport) { // ===================================== // HOME PAGE (with login links) ======== // == ...

Is there a way to adjust the width of the datepicker on my device?

I've been attempting to adjust the width of the date picker, but I'm having trouble achieving it. Below is my code: import React from "react"; import ReactDOM from "react-dom"; import { DatePicker, RangeDatePicker } from &qu ...

What is the best method to evaluate lambda functions in a functional React Component using Jest and Enzyme?

My current challenge involves creating a pulldown tab in a TDD style. I have been struggling to test if the function inside the component triggers on the button's click event. The jest logs keep showing me errors indicating that the object I'm tr ...

The timestamp will display a different date and time on the local system if it is generated using Go on AWS

My angular application is connected to a REST API built with golang. I have implemented a todo list feature where users can create todos for weekly or monthly tasks. When creating a todo, I use JavaScript to generate the first timestamp and submit it to th ...

A comparison of parent and child components

To implement a child-parent component relationship in Angular, first create two JSON files: parent.json and child.json. The parent.json file should contain the following data: "Id":10001, "name":"John" "Id":10002, ...