jQuery Plugin: Add method with .each - javascript

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

Related

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.

disable function using javascript

I can not seem to find the code to disable a javascript function. What I want to do is have a javascript function and then I want to disable it. Here is the code:
<script>
var fooFunc = function fooFunction() {
alert("HELLO");
};
$(document).ready(function() {
fooFunc.disable();
});
</script>
<button onclick="fooFunc()">Button</button>
Basically, when the button is click the function should not work, it should be disabled. Thanks
"Disabling" fooFunc is the same as setting it to an empty function (not to null--that will cause an error when it is called the next time). In this case:
$(document).ready(function() {
fooFunc = function() { };
});
But I don't see how this is different from simply removing the onclick handler from the HTML element.
If you want the ability to disable/re-enable the function, you can write it like this:
fooFunc = function() {
function _fooFunc() {
if (!enabled) return;
alert("HELLO");
}
var enabled = true;
_fooFunc.enable = function() { enabled = true; };
_fooFunc.disable = function() { enabled = false; };
return _fooFunc;
}();
If you want to extend this to allow any function to be enabled/disabled, you can write a higher-order function, which takes any function as a parameter, and returns a function with enable and disable methods attached to it:
function disablable(fn) {
function inner() {
if (!enabled) return;
fn();
}
var enabled = true;
inner.enable = function() { enabled = true; };
inner.disable = function() { enabled = false; };
return inner;
}
Now you can define fooFunc as
var fooFunc = disablable(function fooFunction() {
alert("HELLO");
});
and the rest of your code will work as you want.
You can access the onclick property of the element..
<button id="id" onclick="fooFunc()">Button</button>
<script>
document.querySelector('#id').onclick = '';
</script>
If you don't want the function to work at all and be totally disabled then use the below.
If you want the function to work only under certain conditions then you will need if/else statements so it will work only when the conditions that you have set are met.
$(document).ready(function(){
$("button").onclick(function(event){
event.preventDefault();
});
});
You were going to define it back to undefined or null.
fooFunc=undefined;
You Should be doing this :) Change function definition on very first run and you are good to go.
<! DOCTYPE html>
<html lang="en">
<body>
<script>
var fooFunc = function() {
alert("HELLO");
fooFunc = function(){};
};
var enablefooFunc = function()
{
fooFunc = function() {
alert("HELLO");
fooFunc = function(){};
};
}
</script>
<button onclick="fooFunc()">Run once and Disable FooFunc</button>
<button onclick="enablefooFunc()">Enable FooFunc</button>
</body>
</html>

Define a javascript variable under conditions with jquery

Like the title says, I would like to fill a variable up under some conditions
I thought I could do like that but no :
var content = $(function() {
if ($('#content').length) {
return $('#content');
}
if ($('#content_no_decoration').length) {
return $('#contenu_no_decoration');
}
if ($('#full_content').length) {
return $('#full_content');
}
if ($('#full_content_no_decoration').length) {
return $('#full_content_no_decoration');
}
});
So I thought that the javascript variable 'content' would be one of the jquery object representing an element in the dom. But it seems that 'content' is the function.
I guess you imagine what i want to do.. What is the syntax with JQuery ?
Thank you
$(function() { }) is short-code for the DOMReady event. You need to explicitly define a function, and then assign the return value to your variable.
For example:
function getObj()
{
if($('#content').length)
{
return $('#content');
}
if($('#content_no_decoration').length)
{
return $('#contenu_no_decoration');
}
if($('#full_content').length)
{
return $('#full_content');
}
if($('#full_content_no_decoration').length)
{
return $('#full_content_no_decoration');
}
}
You can then assign the value as :
var content = getObj();
You will need to call the assignment when the DOM is ready though, otherwise the selectors will not trigger as expected. For example:
$(function() {
var content = getObj();
});
You are only declaring the function, so content contains a pointer to the function.
Execute it and you are fine:
var content = function() {
if ($('#content').length) {
return $('#content');
}
if ($('#content_no_decoration').length) {
return $('#contenu_no_decoration');
}
if ($('#full_content').length) {
return $('#full_content');
}
if ($('#full_content_no_decoration').length) {
return $('#full_content_no_decoration');
}
}();
But you don't really need a function here. If the script tag is at the bottom of the page (right before the closing </body>-tag), or the assignment is within a load handler you could use:
var content = $('#content').length
? $('#content')
: $('#content_no_decoration').length
? $('#content_no_decoration')
: $('#full_content').length
? $('#full_content')
: $('#full_content_no_decoration').length
? $('#full_content_no_decoration')
: undefined;
Or use jQuery to your advantage and keep things really short:
var content =
$('#content,#content_no_decoration,#full_content,#full_content_no_decoration')
.get(0);
// if none of the elements exist, content will be undefined, otherwise
// it will contain [a JQuery Object of] the first existing element
why you don't do like that ?
function thatsAGoodName() {
if ($('#content').length) {
return $('#content');
}
if ($('#content_no_decoration').length) {
return $('#contenu_no_decoration');
}
if ($('#full_content').length) {
return $('#full_content');
}
if ($('#full_content_no_decoration').length) {
return $('#full_content_no_decoration');
}
}
var content = thatsAGoodName();
The function
$(function() {
// DOM safe to use do stuff
})
Is shorthand for the document ready event. This tells you the coder that the dom is safe to use.
You would not really return anything from this event.
content is an object because you're setting it to a object here:
var content = $(function() {
What you probably intended was:
var content;
if ($('#content').length) {
content = $('#content');
}
if ($('#content_no_decoration').length) {
content = $('#contenu_no_decoration'); // Is #contenu a typo???
}
if ($('#full_content').length) {
content = $('#full_content');
}
if ($('#full_content_no_decoration').length) {
content = $('#full_content_no_decoration');
}
Note, that this will have a reference to an element now. If you want the actual content you'll need to pull it out with something like html() or val().
You are using the shorthand for the jQuery ready event ($(function() {. What I believe you want is a self invoking function:
// remove the call to jQuery
var content = (function() {
if ($('#content').length) {
return $('#content');
}
// ... more
})(); // invoke the function, which should return a jQuery object
You may need to wrap this in a document.ready, depending on where your script is executed.
Rearrange it a little bit and it should work:
$(function () {
var content = (function() {
var regularContent = $('#content');
if (regularContent.length !== 0) {
return regularContent;
}
var contentNoDecoration = $('#content_no_decoration');
if (contentNoDecoration.length !== 0) {
return contentNoDecoration;
}
var fullContent = $('#full_content');
if (fullContent.length !== 0) {
return fullContent;
}
var fullContentNoDecoration = $('#full_content_no_decoration');
if (fullContentNoDecoration.length !== 0) {
return fullContentNoDecoration;
}
}());
});
This code is basically saying once the DOM is ready (the $(function () { ... }); part), run this anonymous function (the (function () { ... }()); part) and assign its return value to content.
Edit: Also, you're losing efficiency by running each of your selectors twice instead of just once.
It's true that content is the function, but you can use that function. Like:
var result = content();
Edit:
Remove the $() around var content = $({/* code */}) and it works.

How to add values on Javascript?

I'm a very beginner on this and wondering is there anyway that I can add these two values
maxScreenWidth: 480,
menuTitle: 'Menu:'
into this script.
function DropDown(el) {
this.mainNav = el;
this.initEvents();
}
DropDown.prototype = {
initEvents: function () {
var obj = this;
obj.mainNav.on('click', function (event) {
$(this).toggleClass('active');
event.stopPropagation();
});
}
}
$(function () {
var mainNav = new DropDown($('#mainNav'));
$(document).click(function () {
// all dropdowns
$('.dropdown-menu').removeClass('active');
});
});
thanks in advance.
In addition, this is the dropdown menu that I'm applying to my website.
http://tympanus.net/Tutorials/CustomDropDownListStyling/index2.html
I'm trying to apply this menu only for phone layout but it maintains its form no matter what screen size is. It is supposed be disappeared when it's more 480px but it isn't.
Thank you so much for your help.
If you want to add those properties, just add them like below:
function DropDown(el, width, title) {
this.mainNav = el;
this.maxScreenWidth = width; //added
this.menuTitle = title; //added
this.initEvents();
}
Now they are part of your constructor as passable arguments
Then when you call you constructor, just pass what those values should be
$(function () {
var mainNav = new DropDown($('#mainNav'), 480, 'Menu'); //See, pass them here.
$(document).click(function () {
// all dropdowns
$('.dropdown-menu').removeClass('active');
});
});
You can add this values as DropDown parameters as Christoper wrote, also you can create global variables:
var maxScreenWidth = 480;
var menuTitle = 'Menu:';
function DropDown(el) {
this.mainNav = el;
this.initEvents();
}
//...
But then, if you write it in your js file, other code could access and change your global variables (they are global after all :) ), so this technique exists:
(function ($) {
var maxScreenWidth = 480;
var menuTitle = 'Menu:';
function DropDown(el) {
this.mainNav = el;
this.initEvents();
}
//...
}(jQuery));
In the last example you'r creating function with 'private scope', so your 'private' variables ain't accessible from other js code. Also you should note that you couldn't access DropDown from other code in you application, only within this function.

How do I add a function to an element via jQuery?

I want to do something like this:
$('.dynamicHtmlForm').validate = function() {
return true;
}
$('.dynamicHtmlForm .saveButton').click(function() {
if (!$(this).closest('.dynamicHtmlForm').validate()) {
return false;
}
return true;
});
And then when I have a form of class dynamicHtmlForm, I want to be able to provide a custom validate() function:
$('#myDynamicHtmlForm').validate = function() {
// do some validation
if (there are errors) {
return false;
}
return true;
}
But I get this when I do this:
$(this).closest(".dynamicHtmlForm").validate is not a function
Is what I've described even possible? If so, what am I doing wrong?
Yes, it is technically possible. You will need to reference the element itself, however, and not the jQuery collection. This should work:
$('.dynamicHtmlForm').each(function (ix,o) {
o.validate = function() {
return true;
}
});
$('.dynamicHtmlForm .saveButton').click(function() {
if ($(this).closest('.dynamicHtmlForm')[0].validate()) {
return false;
}
return true;
}
jQuery.fn.validate = function(options) {
var defaults = {
validateOPtions1 : '',
validateOPtions2 : ''
};
var settings = $.extend({}, defaults, options);
return this.each(function() {
// you validation code goes here
});
};
$(document).ready(function() {
$('selector').click(function() {
$('some selector').validate();
// or if you used any options in your code that you
// want the user to enter. then you go :
$('some selector').validate({
validateOPtions1: 'value1',
validateOPtions2: 'value2'
});
});
});
You're not adding the function to the element, you're adding it to the jQuery wrapper around the element. Every time you pass a selector to jQuery, it will create a new wrapper for the found elements:
$('#myEl'); // gives a jQuery wrapper object
$('#myEl'); // creates another jQuery wrapper object
If you save the wrapped element to a variable and use that later, it would be a different story because you're accessing the saved jQuery wrapper object.
var dynamicHtmlForm = $('.dynamicHtmlForm');
dynamicHtmlForm.validate = function() {
return true;
}
$('.dynamicHtmlForm .saveButton').click(function() {
if (dynamicHtmlForm.validate()) {
return false;
}
return true;
}
You could also add the function directly to the element using
$('.dynamicHtmlForm')[0].validate = function () { return true; }
// and later...
if (!$(this).closest('.dynamicHtmlForm')[0].validate())
Or you could look at extending jQuery properly by writing a plugin.

Categories

Resources