-2

I'm using the JavaScript snippet below from a theme.

(function(namespace, $) {
    "use strict";

    var AppForm = function() {
        // Create reference to this instance
        var o = this;
        // Initialize app when document is ready
        $(document).ready(function() {
            o.initialize();
        });

    };
    var p = AppForm.prototype;

    // =========================================================================
    // INIT
    // =========================================================================

    p.initialize = function() {
        // Init events
        this._enableEvents();

        this._initRadioAndCheckbox();
        this._initFloatingLabels();
        this._initValidation();
    };

    // =========================================================================
    // EVENTS
    // =========================================================================

    // events
    p._enableEvents = function () {
        var o = this;

        // Link submit function
        $('[data-submit="form"]').on('click', function (e) {
            e.preventDefault();
            var formId = $(e.currentTarget).attr('href');
            $(formId).submit();
        });

        // Init textarea autosize
        $('textarea.autosize').on('focus', function () {
            $(this).autosize({append: ''});
        });
    };

    // =========================================================================
    // RADIO AND CHECKBOX LISTENERS
    // =========================================================================

    p._initRadioAndCheckbox = function () {
        // Add a span class the styled checkboxes and radio buttons for correct styling
        $('.checkbox-styled input, .radio-styled input').each(function () {
            if ($(this).next('span').length === 0) {
                $(this).after('<span></span>');
            }
        });
    };

    // =========================================================================
    // FLOATING LABELS
    // =========================================================================

    p._initFloatingLabels = function () {
        var o = this;

        $('.floating-label .form-control').on('keyup change', function (e) {
            var input = $(e.currentTarget);

            if ($.trim(input.val()) !== '') {
                input.addClass('dirty').removeClass('static');
            } else {
                input.removeClass('dirty').removeClass('static');
            }
        });

        $('.floating-label .form-control').each(function () {
            var input = $(this);

            if ($.trim(input.val()) !== '') {
                input.addClass('static').addClass('dirty');
            }
        });

        $('.form-horizontal .form-control').each(function () {
            $(this).after('<div class="form-control-line"></div>');
        });
    };

    // =========================================================================
    // VALIDATION
    // =========================================================================

    p._initValidation = function () {
        if (!$.isFunction($.fn.validate)) {
            return;
        }
        $.validator.setDefaults({
            highlight: function (element) {
                $(element).closest('.form-group').addClass('has-error');
            },
            unhighlight: function (element) {
                $(element).closest('.form-group').removeClass('has-error');
            },
            errorElement: 'span',
            errorClass: 'help-block',
            errorPlacement: function (error, element) {
                if (element.parent('.input-group').length) {
                    error.insertAfter(element.parent());
                }
                else if (element.parent('label').length) {
                    error.insertAfter(element.parent());
                }
                else {
                    error.insertAfter(element);
                }
            }
        });

        $('.form-validate').each(function () {
            var validator = $(this).validate();
            $(this).data('validator', validator);
        });
    };

    // =========================================================================
    // DEFINE NAMESPACE
    // =========================================================================

    window.materialadmin.AppForm = new AppForm;
}(this.materialadmin, jQuery)); // pass in (namespace, jQuery):

This JavaScript does some UI stuff.

I've also written some jQuery/JS of my own for my application. This jQuery adds and removes HTML from the DOM.

I have a form and two buttons, one being add and one being remove. When the used clicks add/remove it duplicates or removes one of the forms.

After doing so, the effects from the JS above are no longer applied. How can I reapply this every time the DOM is changed?

Noah
  • 874
  • 7
  • 11

1 Answers1

1

You've got an instance of the AppForm function attached to the window object:

window.materialadmin.AppForm = new AppForm;

So can you simply call:

materialadmin.AppForm.initialize();

After you've done your DOM manipulation?

If not, then you're going to need to alter AppForm so that it is applied to future elements (not just the elements it finds in the DOM during initialization). Or provide a wrapper and/or public method that gives you access to the AppForm functionality that's needed after your DOM changes.

Update

Instead of calling initialize() again and binding additional click events, why not change the click events so that they fire on future elements? So instead of:

$('[data-submit="form"]').on('click', function (e) {
  // do stuff
}

Try:

$('body').on('click', '[data-submit="form"]', function (e) {
  // do stuff
}
benjarwar
  • 1,794
  • 1
  • 13
  • 28
  • 1
    the `$('xxx').on` will add a listener on elements that already exists too – Hacketo Aug 26 '15 at 21:05
  • In addition to this, you could also just call the sub-init methods if you only need to do one or the other. `materialadmin.AppForm._initFloatingLabels();`. Of course, this won't solve the issue of the methods possibly attaching multiple event handlers. – Kevin B Aug 26 '15 at 21:06
  • That did it, thanks. – Noah Aug 26 '15 at 21:13