Generic function for jQuery events - javascript

I've got following solution to prevent of multiple clicks (respect only the first one and ignore the rest):
preventMultiClick = function() {
$(this).unbind("click");
$(this).bind("click", function() {
return false;
});
};
preventMultiSubmit = function() {
$(this).unbind("submit");
$(this).bind("submit", function() {
return false;
});
};
$("a").one("click", preventMultiClick);
$("#user").one("submit", preventMultiSubmit);
That solution for me is not elegant I think should be. So I tried upgrade it to following one:
preventMultiClick = function(event) {
$(this).unbind(event);
$(this).bind(event, function() {
return false;
});
};
$("a").one("click", preventMultiClick("click"));
$("#user").one("submit", preventMultiClick("submit"));
and that solution doesn't work. Could somebody explain why or tell me how the function respecting event given as function argument should be written?

The issue is you are calling the function when you are binding the handler, event object is passed to your handler, also event is an object, you should use it's type property.
var preventMultiClick = function(event) {
$(this).unbind(event.type);
$(this).bind(event.type, function() {
return false;
});
};
$("a").one("click", preventMultiClick);
$("#user").one("submit", preventMultiClick);

The problem is that you're passing in an undefined variable rather than the function reference. Instead I would do something like this.
preventMultiClick = function(event) {
$(this).unbind(event.type);
$(this).bind(event.type, function() {
return false;
});
};
$('a').one('click', preventMultiClick);
$('#user').one('submit', preventMultiClick);
Each event contains it's type.

Related

this value of input field .val() not a function

I have this jquery code to check for any value on a given input and then add a simple class if the input has a value.
But in console i receive error that .val() is not a function?
my code is:
$.fn.tkFormControlMaterial = function(){
this
.blur(function () {
if (this.val())
this.addClass('used');
else
this.removeClass('used');
})
.after('<span class="ma-form-highlight"></span><span class="ma-form-bar"></span>');
};
bind will set you free
$.fn.tkFormControlMaterial = function(){
this
.blur(function () {
if (this.val())
this.addClass('used');
else
this.removeClass('used');
}.bind(this))
.after('<span class="ma-form-highlight"></span><span class="ma-form-bar"></span>');
}.bind(this);
I found the solution.
If anyone needs a working sample of my own code above:
$.fn.tkFormControlMaterial = function(){
$(this)
.blur(function () {
if ($(this).val())
$(this).addClass('used');
else
$(this).removeClass('used');
})
.after('<span class="ma-form-highlight"></span><span class="ma-form-bar"></span>');
};
You could also try to use the "self" pattern.
var _self = this;
$.fn.tkFormControlMaterial = function(){
_self
.blur(function () {
if (_self.val())
_self.addClass('used');
else
_self.removeClass('used');
})
.after('<span class="ma-form-highlight"></span><span class="ma-form-bar"></span>');
};

jQuery toggle triggers effect instead of handler [duplicate]

$('.slideArrow').toggle(function (event) {
//some code
}, function (event) {
//some code
});
This works fine for content which are loaded on page-load.But the same function does not work for content loaded with ajax.It just does not intercept the click.
What should I do?
In an other scenario,i faced a same problem(not for toggle,for click) and sorted it this way.I dont know what to do for toggle?
$('.common-parent').on('click','.target-of-click',function(){
//some code
})
The flag method :
var flag = false;
$(document).on('click', '.slideArrow', function(event) {
if (flag) {
// do one thing
}else{
// do another thing
}
flag = !flag;
});
the data method
$(document).on('click', '.slideArrow', function(event) {
if ( $(this).data('flag') ) {
// do one thing
}else{
// do another thing
}
$(this).data('flag', !$(this).data('flag'));
});

Managing and Maintaining too many on click jquery handlers

I recently have been upgrading the Phonegap to the latest version and now it forces me to follow the Chrome's Content Security Policy which in a way is good. But now I am forced to remove the all the onclick handlers in the HTML code and add them in the jquery handler some$(document).ready(function(evt){
$('#addRecordBtn').on('click', function(){
alert("Adding Record");
AddValueToDB();
});
$('#refreshBtn').on('click', function(){
alert("Refresh Records");
ListDBValues();
});
});
But as per what my app is scaled upto I feel that there will be too many of these handlers. Is there an example which shows maintenance of such handlers and a proper way or proper place of defining such handlers.
Here's an idea. You could make an object that stores all of the functions that also knows how to give up the function
var handlers = {
getHandler: function (str) {
return this[str];
},
'#addRecordBtn': function () {
alert("Adding Record");
AddValueToDB();
},
'#refreshBtn': function () {
alert("Refresh Records");
ListDBValues();
}
};
Then apply all of your handlers using this form.
$('#addRecordBtn').on('click', handlers.getHandler('#addRecordBtn'));
$('#refreshBtn').on('click', handlers.getHandler('#refreshBtn'));
Optimization Time if you want to get really fancy and you assign a unique ID to every button as convention
var handlers = {
defer: function () {
return function (){
handlers[$(this).attr('id')](arguments);
};
},
registerHandlers: function () {
for (var key in this) {
if (this.hasOwnProperty(key) && typeof(key) === "string") {
$('#' + key).on('click', this.defer());
}
}
},
'addRecordBtn': function () {
alert("Adding Record");
AddValueToDB();
},
'refreshBtn': function () {
alert("Refresh Records");
ListDBValues();
}
};
call it with
$('#addRecordBtn').on('click', handlers.defer());
$('#refreshBtn').on('click', handlers.defer());
or register everything automatically
handlers.registerHandlers();
Here is a fiddle of my solution
Do you look for something like this?
$('[data-clickhandler]').on('click', function(e) {
var $btn = $(e.currentTarget);
var handler = $btn.data('clickhandler');
alert('Refresh ' + handler);
window[handler] && window[handler](e);
e.preventDefault();
});
Now your elements can specify their clickhandler like so:
<a data-clickhandler="AddValueToDB" href="">...</a>
Or so:
<span data-clickhandler="ListDBValues">...</span>

Stop bind "blur" if click on a link

My bind function:
$searchInput.bind('blur', function() {
$searchResults.remove();
}
But this shouldn't happen if I click on a link inside of $searchResults. Now $searchResults is removed before I can click on a link.
How should I do that?
You may simply set a flag on mouse over $searchResults:
var isOver = false;
$searchInput.bind("blur", function(e) {
if (!isOver) {
$searchResults.remove();
}
});
$searchResults.hover(function() {
isOver = true;
}, function() {
isOver = false;
});
DEMO: http://jsfiddle.net/sUA4D/
You can do the same via element data, e.g. setting $searchResults.data("isOver", true).
One option that comes to mind is to delay the execution of the $.remove() call, like this:
$searchInput.bind('blur', function() {
setTimeout(function() {
$searchResults.remove();
}, 100);
}
$searchInput.find('a').on('click', function() {
$searchResults.remove();
});

Dojo 1.4 how to bind an object

Here is my code:
dojo.provide("test.validation");
dojo.declare("test.validation", null, {
addValidate : function(a) {
this.a = dijit.byId(a);
var link = dojo.connect(dijit.byId("form"), "onclick", this.validate);
},
validate : function(e) {
e.preventDefault();
console.log(this);
if (!this.a.isValid()) {
return false;
}
}
});
I would like call this: this.a.isValid() function, but I'm out of my object scope.
How can I bind it to that onclick event?
Have you tried reading about dojo.hitch()?
It deals exactly with those kind of problems.

Categories