Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i call a function within a js file?

I have a JavaScript file AppForm.js, which I wish to reinitialize after a successful ajax post response.

The file itself contains, among others

(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;

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

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

    p._enableEvents = function () {
       //blah blah blah
       e.preventDefault();
    };

    p._initRadioAndCheckbox = function () {

    };

    p._initFloatingLabels = function () {

    };

    p._initValidation = function () {

    };

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

How can I do that?

$.ajax({
    url: path, type: "POST", cache: "false",
    dataType: "html",
    contentType: "application/json; charset=utf-8",
    traditional: true,
    data: JSON.stringify(postData)
}).success(function (data) {
    $("#products-list").html(data);
    //**PERFORM INIT OF JS FILE**

}).error(function (data) {

});

Thanks to Dan's answer the solution is pretty close but the events are not working since e.preventDefault(); is called.

And here is the full script

(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):

UPDATE 1 I added window.materialadmin.AppForm.Initilize at the ajax response but the events are not working

UPDATE 2 And here is the code that does not work after the postback.

$(".ProductOnlyForDemonstation, .IncludeInMainPage, .Active")
    .on('click', 'button', function(){
        $('.sweet-overlay').toggle();
        if (jQuery("#FORM").valid()) {
            var id = $(this).attr("data-id");
            $.post("/product/DemoIncludeActive", {
                "Id": id,
                "ProductOnlyForDemonstation": $("#ProductOnlyForDemonstation-" + id).is(':checked'),
                "IncludeInMainPage": $("#IncludeInMainPage-" + id).is(':checked'),
                "Active": $("#Active-" + id).is(':checked'),
            },
            function (data) {

            }).success(function (data) {

            }).error(function () {

            });
        }
    });
like image 845
OrElse Avatar asked Mar 27 '16 13:03

OrElse


People also ask

How do you access a function in another .js file?

In JavaScript, variables can be accessed from another file using the <script> tags or the import or export statement.

How do you call my function in JavaScript?

The JavaScript call() Method It can be used to invoke (call) a method with an owner object as an argument (parameter). With call() , an object can use a method belonging to another object.

How do you call one function from another in JavaScript?

To call a function inside another function, define the inner function inside the outer function and invoke it. When using the function keyword, the function gets hoisted to the top of the scope and can be called from anywhere inside of the outer function.


3 Answers

You can wrap your code in a global function.

(function(namespace, $) {
  "use strict";
  window.main = function() {
    var AppForm = function () {
    // ...
    };
  };

  window.main(); // you can initialize it here
)(this.materialadmin, jQuery);

And execute it if the response is successful.

.success(function (data) {
  $("#products-list").html(data);
  //**PERFORM INIT OF JS FILE**
  window.main();
}).error(function (data) {

});

Edit: It looks like you're exposing the initialize method on a global object. You can just call that init method when the AJAX response completes.

.success(function (data) {
  $("#products-list").html(data);
  //**PERFORM INIT OF JS FILE**
  window.materialadmin.AppForm.initialize();
}).error(function (data) {

});
like image 75
Dan Prince Avatar answered Oct 25 '22 14:10

Dan Prince


some checks for the events to work after postback

1)using $("#products-list").html(data) will remove all the events attached to child elements of #products-list.

So either a)attach events once on "#products-list" only with event-delegation In jQuery, how to attach events to dynamic html elements? or b)reattach events on every child after using $("#products-list").html(data)

2) dont use .html() because it also removes all jquery data and events on children. update independent children elements instead.

like image 1
Shishir Arora Avatar answered Oct 25 '22 16:10

Shishir Arora


Related to UPDATE 2

Try to register your events with delegation:

$(document).on(
    'click',
    '.ProductOnlyForDemonstation button, .IncludeInMainPage button, .Active button',
    function() {
        // Your code
    }
);

I suppose you're loading something and render new page content after response, so previously registered events are not attached to new elements. With delegation you'll get your events working even after elements were added to DOM dynamically (if they match with delegating selector), because events are attached to document and bubbled from your buttons. You can attach event deeper in the DOM than document itself, but to the element containing your dynamic content (in other words: to closest element that will not be overriden after completing request).

PS. You can also add some unique class to all .ProductOnlyForDemonstation button, .IncludeInMainPage button, .Active button and delegate events to that class (shorter definition)

like image 2
Wirone Avatar answered Oct 25 '22 15:10

Wirone