I'm creating a plugin for jQuery. I wont attempt to explain the plugin here, so lets say for simplicity that my plugin opens an alert when you click on the targeted element. Here is a simple version of my plugin.
(function($) {
// Options
var defaults = {
message: 'Default message'
};
var options = $.extend(defaults, options);
$.fn.jAlert = function(options) {
return this.each(function(){
var $this = $(this);
$this.click(function(){
alert(options.message);
});
});
};
})(jQuery);
I can get that far. It works great. However, if I call my plugin like this:
$('h1.simon').plugin({ message: 'Hello ' + $(this).attr('class') });
The message returns as 'Hello undefined', I'd prefer it to be 'Hello simon' (the class of the H1 tag).
I'm sure this is the simplest thing to do, but I'm not even sure what I should be Googling to find the solution.
Any help would be greatly appreciated!
Cheers,
Will
Update:
After playing about a bit, this seems to work... And I have no idea why! I don't think I really understand scope yet. I think I'll go do some reading.
$('h1.simon').click(function(){
$(this).jAlert({
icon: 'Hello ' + $(this).attr('class')
});
});
Save a reference to the element:
var $el = $('h1.simon');
$el.plugin({ message: 'Hello ' + $el.attr('class') });
Otherwise this refers to window which doesn't have a class.
If you want to be able to use this for convenience, you could allow message to accept a function that returns the value you want to display.
Try it out: http://jsfiddle.net/9hyJc/
(function($) {
$.fn.jAlert = function(options) {
// Options
var defaults = {
message: 'Default message'
};
var options = $.extend(defaults, options);
return this.each(function(){
var $this = $(this);
$this.click(function(){
if($.isFunction(options.message)) {
// If it is a function, call it,
// setting "this" to the current element
alert(options.message.call(this));
} else {
// Otherwise, assume it is a string
alert(options.message);
}
});
});
};
})(jQuery);
$('h1.simon').jAlert({ message: function() { return 'Hello ' + $(this).attr('class'); } });
at the time you are calling the plugin and passing the options .. this refers to window and NOT the element as you seem to expect
Related
Normally when writing jQuery i just use functions. This time I want to give it a little sprinkle of best practice and so I followed a tutorial. The javascript itself seems to be correct but I am having a few problems calling certain functions.
jQuery.noConflict();
(function($j) {
'use strict';
function Site(settings) {
this.windowLoaded = false;
}
Site.prototype = {
constructor: Site,
start: function() {
var me = this;
$j(window).load(function() {
me.windowLoaded = true;
});
this.attach();
},
attach: function() {
this.getPrimaLink();
this.onCloseDialog();
this.triggerDialog();
this.openLink();
},
getPrimaLink: function(){
if($j('#order-data').is(":visible")){
$j( ".content-header" ).append($j( "#findPrimaLink" ));
$j('#findPrimaLink').show();
}
},
onCloseDialog: function(){
$j('#dialog').bind('dialogclose', function(event) {
$j( ".content-header" ).append($j( "#findPrimaLink" ));
$j('#findPrimaLink').show();
});
},
triggerDialog: function(){
$j("[title='Create New Customer']").click(function(){
$j('#findPrimaLink').show();
>>>>> this.openDialog(); <<<<<<
})
},
openLink: function(){
$j('#findPrimaLink').click(function(){
>>> this.openDialog(); <<<<<
});
},
openDialog: function(){
$j( "#dialog" ).dialog({
height: 'auto',
width: 350,
modal: true,
resizable:false,
});
},
};
$j(document).ready(function($j) {
var site = new Site();
site.start();
});
})(jQuery);
Within the start and attach function I am able to call each function by placing 'this' in front of it. But when I try to call openDialog() from openLink() and triggerDialog() I get - Uncaught TypeError: undefined is not a function.
Why is this and what should I do to fix it?
For both functions you're having a problem with, you're trying to use this inside of a jQuery function, so this's scope is to the DOM element, not the Site class.
triggerDialog: function(){
var site = this;
$j("[title='Create New Customer']").click(function(){
$j('#findPrimaLink').show();
site.openDialog();
console.log(this); //remove this for production, but you can see that `this` points to a DOM element
})
},
openLink: function(){
var site = this;
$j('#findPrimaLink').click(function(){
site.openDialog();
});
},
To understand why this happens, you should read about javascript Closures. Here and here.
P.S. you have an extra comma after your openDialog function.
P.P.S. It's also worth noting that this is exactly what're you're doing inside the start method.
var me = this;
$j(window).load(function() {
me.windowLoaded = true;
});
I'm using selecter jquery. I initialize it by typing the code
$("select").selecter();
I need to make sure that the formstone selecter jquery library has completed before i start appending elements. So what i did is to is use the $.when function
initialize: function(){
$.when($("select").selecter()).then(this.initOptions());
},
initOptions: function(){
this.$el.find('.selecter').addClass('something');
}
But this does not work. How can i wait while formstone selecter is doing its thing before i execute another function?
Thanks,
UPDATE
Here's the update of what i did but it does not work.
initialize: function(){
$("select").selecter({callback: this.initOptions });
},
initOptions: function(){
this.$el.find('.selecter').addClass('something');
}
There is a callback option.
The function passed as a callback will receive the newly selected value as the first parameter
Should be $("select").selecter(callback: function() { alert('callback fired.') });
or as shown
$("select").selecter({
callback: selectCallback
});
function selectCallback(value, index) {
alert("VALUE: " + value + ", INDEX: " + index);
}
The problem which I think regarding the callback edited code is that this can refer to anything. Try the following code
var selectorObj = {
initialize: function(){
$("select").selecter({callback: selectorObj.initOptions });
},
initOptions: function(){
this.$el.find('.selecter').addClass('something');
}
};
Created a working fiddler for you http://jsfiddle.net/6Bj6j/
The css is out of shape. Just select what is poping up when you click on the dropdown. You will get an alert which is written in the callback.
The problem with the provided snippet is the scope of the callback:
var selectorObj = {
initialize: function(){
$("select").selecter({ callback: selectorObj.initOptions });
},
initOptions: function(){
// 'this' refers to the "$('.selecter')" jQuery element
this.addClass('something');
}
};
However if you just need to add a class to the rendered element, you should use the 'customClass' option:
$("select").selecter({
customClass: "something"
});
If you need to do more, you can always access the Selecter element directly:
var $selecter = $("select").selecter().next(".selecter");
$selecter.addClass("something").find(".selecter-selected").trigger("click");
Sidenote: I'm the main developer of Formstone. If you have any suggestions for new features or better implementation, just open a new issue on GitHub.
Sorry for how stupid this is going to sound. My JS vocabulary is terrible and I had absolutely no idea what to search for.
I'm using jQuery.
So I've got this code:
var example = {
open: function(element){
alert(element.text());
},
init: function(){
$("a").click(example.open);
}
};
$(document).ready(function(){example.init();)
So here's the problem: I want to pass an argument to example.open() when I click the "a" element. It doesn't seem like I can, though. In order for the example.open method to just…exist on page-load and not just run, it can't have parentheses. I think. So there's no way to pass it an argument.
So I guess my question is…how do you pass an argument to a function that can't have parentheses?
Thanks so much.
Insert another anonymous function:
var example = {
open: function(element){
alert(element.text());
},
init: function(){
$("a").click(function()
{
example.open($(this));
});
}
};
You can also try this version because jQuery set the function's context (this) to the DOM element:
var example = {
open: function(){
alert($(this).text());
},
init: function(){
$("button").click(example.open);
}
};
Since jQuery binds the HTML element that raised the event into the this variable, you just have to pass it as a regular parameter:
var example = {
open: function(element){
alert(element.text());
},
init: function(){
$("a").click(function() {
// jQuery binds "this" to the element that initiated the event
example.open(this);
});
}
}
$(document).ready(function(){example.init();)
You can pass the anchor through its own handler:
var example = {
open: function( element ){
alert(element.text());
},
init: function(){
$("a").on("click", function() {
example.open( $(this) );
});
}
};
$(document).ready(function() {
example.init();
});
I don't understand what you actually want to do;
however, I can give a try:
var example = {
open: function(event){
event.preventDefault();
alert($(event.target).text()+' : '+event.data.x);
},
init: function(){
$("a").bind('click',{x:10},example.open);
}
};
$(example.init);
demo:
http://jsfiddle.net/rahen/EM2g9/2/
Sorry, I misunderstood the question.
There are several ways to handle this:
Wrap the call in a function:
$('a').click( function(){ example.open( $(this) ) } );
Where $(this) can be replaced by your argument list
Call a different event creator function, which takes the arguments as a parameter:
$('a').bind( 'click', {yourvariable:yourvalue}, example.open );
Where open takes a parameter called event and you can access your variable through the event.data (in the above it'd be event.data.yourvariable)
Errors and Other Info
However your element.text() won't just work unless element is a jQuery object. So you can jQueryify the object before passing it to the function, or after it's received by the function:
jQuery the passed object:
function(){ example.open(this) } /* to */ function(){ example.open($(this)) }
jQuery the received object:
alert(element.text()); /* to */ alert($(element).text());
That said, when calling an object without parameters this will refer to the object in scope (that generated the event). So, really, if you don't need to pass extra parameters you can get away with something like:
var example = {
open: function(){ // no argument needed
alert($(this).text()); // this points to element being clicked
},
init: function(){
$("a").click(example.open);
}
};
$(document).ready(function(){
example.init();
}); // your ready function was missing closing brace '}'
I wonder if selector "$cacheA" will be cached on page load in the example below?
// MY JQUERY FUNCTION/PLUGIN
(function( $ ){
$.fn.myFunction = function() {
var $cacheA = this,
$cacheB = $cacheA.children(),
$cacheC = $cacheB.eq(0);
$cacheD = $cacheA.parent();
$cacheD.click(function(){
$cacheA.toggle();
$cacheB.fadeIn();
$cacheC.slideUp();
});
};
})( jQuery );
// END JQUERY FUNCTION/PLUGIN
$(window).load(function(){
$('#mySelector').myFunction();
});
Would it be any reason to do this:
$(window).load(function(){
var $mySelector = $('#mySelector');
$mySelector.myFunction();
});
If, inside your "load" handler, you were to do many jQuery operations with "$mySelector", then saving that in a variable would be a good idea. However, in your example, you only use the value once, so it really makes no difference at all.
Firstable, $cacheA and others inside click function will be undefined.
$cacheD.click(function(){
$cacheA.toggle();
$cacheB.fadeIn();
$cacheC.slideUp();
});
Second,
$.fn.myFunction = function() {
var $cacheA = this,
$cacheB = $cacheA.children(),
$cacheC = $cacheB.eq(0);
$cacheD = $cacheA.parent();
}
So, after $('selector').myFunction() how can I use $cacheB, $cacheC and $cacheD? Where they are will store?
I've written this code for a friend. The idea is he can add a "default" class to his textboxes, so that the default value will be grayed out, and then when he clicks it, it'll disappear, the text will return to its normal color, and then clicking a second time won't clear it:
$(document).ready(function() {
var textbox_click_handler = function clear_textbox() {
$(this).removeClass('default');
$(this).attr('value', '');
$(this).unbind(textbox_click_handler);
};
$(".default").mouseup(textbox_click_handler);
});
The clicking-to-clear works, but I get the following error:
Uncaught TypeError: Object function clear_textbox() { ... } has no method 'split'
what is causing this? How can I fix it? I would just add an anonymous function in the mouseup event, but I'm not sure how I would then unbind it -- I could just unbind everything, but I don't know if he'll want to add more functionality to it (probably not, but hey, he might want a little popup message to appear when certain textboxes are clicked, or something).
How can I fix it? What is the 'split' method for? I'm guessing it has to do with the unbind function, since the clearing works, but clicking a second time still clears it.
You can do it like this:
var textbox_click_handler = function(e) {
$(this).removeClass('default')
.attr('value', '')
.unbind(e.type, arguments.callee);
};
$(function() {
$(".default").mouseup(textbox_click_handler);
});
Or use the .one function instead that automatically unbinds the event:
$(function() {
$(".default").one('mouseup', function() {
$(this).removeClass('default').attr('value', '');
});
});
The unbind needs an event handler while you are specifying a function to its argument thereby giving you the error.
I am not sure if this is really different but try assigning the function to a variable:
var c = function clear_textbox() {
$(this).removeClass('default');
$(this).attr('value', '');
$(this).unbind('mouseup');
}
and then:
$(".default").mouseup(function(){
c();
});
if you don't want to completely unbind mouseup, check for the current state using hasClass(). No need to unbind anything.
$(document).ready(function() {
$('.default').bind('mouseup', function(e) {
var tb = $(this);
if(tb.hasClass('default')) {
tb.removeClass('default').val('');
}
});
});
Make sure you are unbinding mouseup:
function clear_textbox() {
$(this).removeClass('default');
$(this).attr('value', '');
$(this).unbind('mouseup');
}
$(function() {
$('.default').mouseup(clear_textbox);
});
Also I would write this as a plugin form:
(function($) {
$.fn.watermark = function(settings) {
this.each(function() {
$(this).css('color', 'gray');
$(this).mouseup(function() {
var $this = $(this);
$this.attr('value', '');
$this.unbind('mouseup');
});
});
return this;
};
})(jQuery);
so that your friend can simply:
$(function() {
$('.someClassYourFriendUses').watermark();
});