javascriptjquerydomthismodule-pattern

How to access outside .this in object


I'm trying to rewrite my functional code to module pattern js, and I have this issue - When I try to delete input field which is dynamically created, I use jQuery $(this) to access dom element and delete its parent 'div'. But this refers to the Modal object, not the component I clicked. How to solve it, without making some field counter and creating fields with unique ID's, then catching ids on click and deleting that input field?

My modal:

var s,
    Modal = {
        settings: {
            addInputBtn: $("#add-input"),
            inputContainer: $("#modal-input-form"),
            checkBoxesList: $(".check-box"),
            inputFieldsList: $(".form-control"),
            inputFieldsOptionalList: $(".optional-modal"),
            inputHtml: `
                <div class="input-group mb-3 optional-modal">
                    <div class="input-group-prepend">
                        <div class="input-group-text">
                            <input type="checkbox" class="check-box">
                        </div>
                    </div>
                    <input type="text" class="form-control">
                    <button type="button" class="close">
                        <span>&times;</span>
                    </button>
                </div>`
        },
        init: function () {
            s = this.settings;
            this.bindUIActions();
        },

        bindUIActions: function () {
            s.addInputBtn.on("click", () => Modal.addInput());
            s.inputContainer.on("click", ".close", () => Modal.deleteInput());
        },

        addInput: function () {
            s.inputContainer.append(s.inputHtml);
        },

        deleteInput: function () {);
            $(this).parent('div').remove();
        }
    }
    Modal.init();

enter image description here


Solution

  • deleteInput: function (e) {);
                $(e.target).parent('div').remove();
            }
    

    Event handlers are passed an event argument. Among its useful properties is target, which is the html element that the event originated on. Note that it could be different from the this of the event handler, which is the element that the event handler is attached to, as events bubble up through the DOM. So if you have this html:

    <div id="parent">
      <div id="child"></div>
    </div>
    

    then for this JS function:

    $("#parent").on('click', function(e){
      //this will equal <div id="parent"> unless you bind the handler to something else
      //e.target will equal the clicked element:
      //if the user clicked the child, it will equal the child;
      //if the user clicked parent directly, it will equal parent.
      $(e.target).closest('#parent').doSomething();
    });