this.init is not a function jquery validation plugin in react app - javascript

I have form in my react application, which validates via jquery validation plugin.
let validator = $('form').validate({
errorClass: 'has-error',
errorElement:'label',
});
validator.form();
if ($('.has-error').length > 0) {
$('.has-error').each(function (index) {
$.validator().showErrors({prop:$(this).data('error')});
});
} else {
/*work with data*/
}
All errors messages showing fine, but every time when validation triggered, I get error in console:
this.init is not a function
And link me to code in plugin script:
$.validator = function( options, form ) {
this.settings = $.extend( true, {}, $.validator.defaults, options );
this.currentForm = form;
this.init();
};
How can I fix it?
UPD 1: below in the plugin script code i found this code:
$.extend( $.validator, {
//some code
prototype: {
init: function() {
this.labelContainer = $( this.settings.errorLabelContainer );
this.errorContext = this.labelContainer.length && this.labelContainer || $( this.currentForm );
this.containers = $( this.settings.errorContainer ).add( this.settings.errorLabelContainer );
this.submitted = {};
this.valueCache = {};
this.pendingRequest = 0;
this.pending = {};
this.invalid = {};
this.reset();
//some code
Maybe it fires error exception because of this init function?

I think the problem is in this line:
$.validator().showErrors({prop:$(this).data('error')});
$.validator function is a constructor so it must always be used with new keyword. If you call it as normal function this inside this function points to global window (or is undefined in strict mode) which doesn't have init method

Related

How to hook on library function (Golden Layout) and call additional methods

I'm using a library called Golden Layout, it has a function called destroy which will close all the application window, on window close or refesh
I need to add additional method to the destroy function. I need to removeall the localstorage aswell.
How do i do it ? Please help
Below is the plugin code.
lm.LayoutManager = function( config, container ) {
....
destroy: function() {
if( this.isInitialised === false ) {
return;
}
this._onUnload();
$( window ).off( 'resize', this._resizeFunction );
$( window ).off( 'unload beforeunload', this._unloadFunction );
this.root.callDownwards( '_$destroy', [], true );
this.root.contentItems = [];
this.tabDropPlaceholder.remove();
this.dropTargetIndicator.destroy();
this.transitionIndicator.destroy();
this.eventHub.destroy();
this._dragSources.forEach( function( dragSource ) {
dragSource._dragListener.destroy();
dragSource._element = null;
dragSource._itemConfig = null;
dragSource._dragListener = null;
} );
this._dragSources = [];
},
I can access the destroy method in the component like this
this.layout = new GoldenLayout(this.config, this.layoutElement.nativeElement);
this.layout.destroy();`
My code
#HostListener('window:beforeunload', ['$event'])
beforeunloadHandler(event) {
var originalDestroy = this.layout.destroy;
this.layout.destroy = function() {
// Call the original
originalDestroy.apply(this, arguments);
localStorage.clear();
};
}
Looking at the documentation, GoldenLayout offers an itemDestroyed event you could hook to do your custom cleanup. The description is:
Fired whenever an item gets destroyed.
If for some reason you can't, the general answer is that you can easily wrap the function:
var originalDestroy = this.layout.destroy;
this.layout.destroy = function() {
// Call the original
originalDestroy.apply(this, arguments);
// Do your additional work here
};
You may be able to do this for all instances if necessary by modifying GoldenLayout.prototype:
var originalDestroy = GoldenLayout.prototype.destroy;
GoldenLayout.prototype.destroy = function() {
// Call the original
originalDestroy.apply(this, arguments);
// Do your additional work here
};
Example:
// Stand-in for golden laout
function GoldenLayout() {
}
GoldenLayout.prototype.destroy = function() {
console.log("Standard functionality");
};
// Your override:
var originalDestroy = GoldenLayout.prototype.destroy;
GoldenLayout.prototype.destroy = function() {
// Call the original
originalDestroy.apply(this, arguments);
// Do your additional work here
console.log("Custom functionality");
};
// Use
var layout = new GoldenLayout();
layout.destroy();
Hooking into golden layout is the intended purpose for the events.
As briefly touched on by #T.J. Crowder, there is the itemDestroyed event which is called when an item in the layout is destroyed.
You can just listen for this event like such:
this.layout.on('itemDestroyed', function() {
localStorage.clear();
})
However, this event is called every time anything is destroyed, and propagates down the tree, even just by closing a tab. This means that if you call destroy on the layout root, you will get an event for every RowOrColumn, Stack and Component
I would recommend to check the item passed into the event and ignore if not the main window (root item)
this.layout.on('itemDestroyed', function(item) {
if (item.type === "root") {
localStorage.clear();
}
})

jQuery Plugin: Add method with .each

I have the following code in a jQuery plugin:
$.fn.myForm = function() {
return this.each(function() {
var myForm = new MyForm(this);
$.data(myForm, 'myForm');
});
};
I thought that doing this, would allow me to then access the inner functions of myForm, such as getForm
var MyForm = function() {
//...
function getForm() {
return 'Hi';
}
}
But when I try to access myForm from outside the plugin, I get undefined:
$('#test').myForm();
$('#test').data('myForm')
> undefined
What am I doing wrong here?
set your data like this:-
$(this).data('myForm', myForm);

jQuery plugin instances variable with event handlers

I am writing my first jQuery plugin which is a tree browser. It shall first show the top level elements and on click go deeper and show (depending on level) the children in a different way.
I got this up and running already. But now I want to implement a "back" functionality and for this I need to store an array of clicked elements for each instance of the tree browser (if multiple are on the page).
I know that I can put instance private variables with "this." in the plugin.
But if I assign an event handler of the onClick on a topic, how do I get this instance private variable? $(this) is referencing the clicked element at this moment.
Could please anyone give me an advise or a link to a tutorial how to get this done?
I only found tutorial for instance specific variables without event handlers involved.
Any help is appreciated.
Thanks in advance.
UPDATE: I cleaned out the huge code generation and kept the logical structure. This is my code:
(function ($) {
$.fn.myTreeBrowser = function (options) {
clickedElements = [];
var defaults = {
textColor: "#000",
backgroundColor: "#fff",
fontSize: "1em",
titleAttribute: "Title",
idAttribute: "Id",
parentIdAttribute: "ParentId",
levelAttribute: "Level",
treeData: {}
};
var opts = $.extend({}, $.fn.myTreeBrowser.defaults, options);
function getTreeData(id) {
if (opts.data) {
$.ajax(opts.data, { async: false, data: { Id: id } }).success(function (resultdata) {
opts.treeData = resultdata;
});
}
}
function onClick() {
var id = $(this).attr('data-id');
var parentContainer = getParentContainer($(this));
handleOnClick(parentContainer, id);
}
function handleOnClick(parentContainer, id) {
if (opts.onTopicClicked) {
opts.onTopicClicked(id);
}
clickedElements.push(id);
if (id) {
var clickedElement = $.grep(opts.treeData, function (n, i) { return n[opts.idAttribute] === id })[0];
switch (clickedElement[opts.levelAttribute]) {
case 1:
renderLevel2(parentContainer, clickedElement);
break;
case 3:
renderLevel3(parentContainer, clickedElement);
break;
default:
debug('invalid level element clicked');
}
} else {
renderTopLevel(parentContainer);
}
}
function getParentContainer(elem) {
return $(elem).parents('div.myBrowserContainer').parents()[0];
}
function onBackButtonClick() {
clickedElements.pop(); // remove actual element to get the one before
var lastClickedId = clickedElements.pop();
var parentContainer = getParentContainer($(this));
handleOnClick(parentContainer, lastClickedId);
}
function renderLevel2(parentContainer, selectedElement) {
$(parentContainer).html('');
var browsercontainer = $('<div>').addClass('myBrowserContainer').appendTo(parentContainer);
//... rendering the div ...
// for example like this with a onClick handler
var div = $('<div>').attr('data-id', element[opts.idAttribute]).addClass('fct-bs-col-md-4 pexSubtopic').on('click', onClick).appendTo(subtopicList);
// ... rendering the tree
var backButton = $('<button>').addClass('btn btn-default').text('Back').appendTo(browsercontainer);
backButton.on('click', onBackButtonClick);
}
function renderLevel3(parentContainer, selectedElement) {
$(parentContainer).html('');
var browsercontainer = $('<div>').addClass('myBrowserContainer').appendTo(parentContainer);
//... rendering the div ...
// for example like this with a onClick handler
var div = $('<div>').attr('data-id', element[opts.idAttribute]).addClass('fct-bs-col-md-4 pexSubtopic').on('click', onClick).appendTo(subtopicList);
// ... rendering the tree
var backButton = $('<button>').addClass('btn btn-default').text('Back').appendTo(browsercontainer);
backButton.on('click', onBackButtonClick);
}
function renderTopLevel(parentContainer) {
parentContainer.html('');
var browsercontainer = $('<div>').addClass('fct-page-pa fct-bs-container-fluid pexPAs myBrowserContainer').appendTo(parentContainer);
// rendering the top level display
}
getTreeData();
//top level rendering! Lower levels are rendered in event handlers.
$(this).each(function () {
renderTopLevel($(this));
});
return this;
};
// Private function for debugging.
function debug(debugText) {
if (window.console && window.console.log) {
window.console.log(debugText);
}
};
}(jQuery));
Just use one more class variable and pass this to it. Usually I call it self. So var self = this; in constructor of your plugin Class and you are good to go.
Object oriented way:
function YourPlugin(){
var self = this;
}
YourPlugin.prototype = {
constructor: YourPlugin,
clickHandler: function(){
// here the self works
}
}
Check this Fiddle
Or simple way of passing data to eventHandler:
$( "#foo" ).bind( "click", {
self: this
}, function( event ) {
alert( event.data.self);
});
You could use the jQuery proxy function:
$(yourElement).bind("click", $.proxy(this.yourFunction, this));
You can then use this in yourFunction as the this in your plugin.

Where to implement a window.resize function in jquery-boilerplate?

I'm trying to convert one of my plugin written with the jquery plugin pattern with the one provided by jquery-boilerplate. My plugin relies on a $( window ).resize() function to make it responsive, however when I try to use it on the jquery-boilerplate the web console returns a TypeError when I resize the window browser:
function Plugin ( element, options ) {
this.element = element;
this.cfg = $.extend( true, defaults, options );
this._defauls = defaults;
this._name = pluginName;
this.init();
}
// Avoid Plugin.prototype conflicts
$.extend( Plugin.prototype, {
init: function() {
this.windowWidth();
$(window).resize(function(){
this.windowWidth();
});
},
windowWidth: function() {
var w = $( window ).width();
console.log(w);
}
} );
Web console returns:
TypeError: this.windowWidth is not a function.
I tried in this way too:
function Plugin ( element, options ) {
this.element = element;
this.cfg = $.extend( true, defaults, options );
this._defaults = defaults;
this._name = pluginName;
this.init();
$(window).resize(function(){
this.init();
});
}
// Avoid Plugin.prototype conflicts
$.extend( Plugin.prototype, {
init: function() {
this.windowWidth();
},
windowWidth: function() {
var w = $( window ).width();
console.log(w);
}
} );
and the web console returns:
TypeError: this.init is not a function.
Where do I have to put code that have to listen to the jquery resize method according to the jquery-boilerplate?
I basically made it work in this way:
function Plugin ( element, options ) {
var element = $( element ),
cfg = $.extend( true, defaults, options ),
windowWidth = function() {
return $( window ).width();
};
console.log( windowWidth() );
$(window).resize(function(){
console.log( windowWidth() );
});
}
But this isn't the purpose of the jquery-boilerplate team, so how can I do this while using the jquery-boilerplate plugin pattern?
This error has nothing to do with jquery-boilerplate.
You definitely should learn more about "this" keyword in Javascript before writing any plugins.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this

apply / trigger not passing correct parameters

I've run into a strange problem with my jQuery code. I have a setup as follows:
(function($) {
var o = $({});
$.subscribe = function() { o.on.apply(o, arguments); };
$.publish = function() { o.trigger.apply(o, arguments); };
}(jQuery));
(function($) {
var CarrierView = {
subscriptions: function() {
$.subscribe( 'reporting.carrier.model.changed', this.renderModel );
},
renderModel: function( e, data ) {
var self = CarrierView;
}
};
var CarrierModel = {
subscriptions: function() {
$.subscribe( 'reporting.carrier.model.update', this.updateModel );
},
updateModel: function( value ) {
$.getJSON('carriers', function( data ) {
$.publish( 'reporting.carrier.model.changed', data );
});
}
};
window.CarrierView = CarrierView.init();
window.CarrierModel = CarrierModel.init();
})(jQuery);
Running a very basic pub/sub. My issue is the following:
A click event triggers the CarrierModel.updateModel method, which calls $.getJSON. The data returned is an Array[99], which is then published. When CarrierView.renderModel is called, the data there is the first element of the Array[99], an Array[5]. What am I doing incorrectly? How do I pass the whole set of data to the View?

Categories

Resources