Javascript call class w/o parenthesis (jQuery style) - javascript

I am trying to set up library like jQuery simply for learning purposes. I have it working decently well, and I can do method chaining as needed. The problem I am having is being able to call a method with the class' parenthesis:
What I have to do:
$foo().get('id1');
What I would like to do:
$foo.get('id1');
Here is the current javascript:
(function( window ) {
var document = window.document;
var fooTools = (function() {
var fooTools = function( selector ) {
return new fooTools.base.init( selector );
};
fooTools.base = fooTools.prototype = {
init: function( selector ) {
if( !selector ) {
return this;
}
if( selector ) {
this[0] = selector;
this.length = 1;
return this;
}
},
get: function( id ) {
return document.getElementById( id );
},
//..other methods
};
fooTools.base.init.prototype = fooTools.base;
return fooTools;
}());
window.fooTools = window.$foo = fooTools;
}( window ));
Currently it works just fine, but if I do not include the parenthesis I get an error that the .get() method does not exist. I still want to maintain the ability to use parenthesis for other methods, so i just want it be optional. Thanks!

change:
window.fooTools = window.$foo = fooTools;
to:
window.$foo = new fooTools();
window.fooTools = fooTools;
Live Example
EDIT
window.fooTools = fooTools;
window.$foo= fooTools;
window.$foo.get = fooTools.prototype.get;
Updated Example

Define two different kind of methods, just like we do in jQuery.
If the method needs parenthesis such as $foo('id1').attr({...}) define it using $foo.prototype.method = function, else, define it as a property of $foo $foo.get = function(){...}
Edit: This is actually based on IAbstract's answer.
It would be fooTools.prototype not $foo.prototype since fooTools is the class that $foo is an instance of.

Then you need to define $foo as something other than a function--right now you're returning fooTools, which is a function, so you need to call it in order to access what it exposes.
(Drat, he beat me to it.)

Related

Extend jQuery Plugin with additional function / override function

I need to extend a jQuery Plugin (https://github.com/idiot/unslider) in order to add additional behavior with another public method.
(function(){
// Store a reference to the original remove method.
var originalMethod = $.fn.unslider;
// Define overriding method.
$.fn.unslider = function(){
// Execute the original method.
originalMethod.apply( this, arguments );
console.log( "Override method" );
function test() {
console.log("test called");
}
this.each(function() {
// Operations for each DOM element
console.log("each dom element?");
}).data('unslider', {
// Make test accessible from data instance
test: test
});
return this;
}
})(jQuery);
I already managed to make the public method accessible when calling
var slider = $('#slider');
slider.data('unslider').test();
However, I want to keep the old behavior of unslider anyways, but extend the Plugin with another function. Does anyone have an idea?
I created a fiddle, so you can check whats happening:
My new function gets called, but the old ones are gone:
http://jsfiddle.net/b2os4s7e/1/
If you look at the source of unslider, you can see it stores the Unslider instance inside the data:
// Enable multiple-slider support
return this.each(function(index) {
// Cache a copy of $(this), so it
var me = $(this),
key = 'unslider' + (len > 1 ? '-' + ++index : ''),
instance = (new Unslider).init(me, o);
// Invoke an Unslider instance
me.data(key, instance).data('key', key);
});
In your code you're overwriting this object with your own object. However, the slider expects there to be an Unslider instance. So what you want to do is get this instance and then extend it with your own functions:
var key = $(this).data('key');
var obj = $(this).data(key);
obj.test = function() { console.log('Working!'); };
See http://jsfiddle.net/b2os4s7e/2/
Just define:
$fn.unslider2 = function() { ... }
With any name and behaviour you like.
For extend JQuery should use .fn.extend
(function($){
$.fn.extend({
helloworld: function(message){
return this.each(function(){
$(this).click(function(){
alert(message);
});
});
}
});
})(jQuery)
the object .fn.extend is used for extend funcionality of jQuery
Thanks for your answers! I did it this way:
(function($){
var originalMethod = $.fn.unslider;
$.fn.extend({
unslider: function(o) {
var len = this.length;
var applyMethod = originalMethod.apply( this, arguments );
var key = applyMethod.data('key');
var instance = applyMethod.data(key);
// Cache a copy of $(this), so it
var me = $(this);
if (instance) {
instance.movenext = function (callback) {
return instance.stop().to(instance.i + 1, callback);
};
instance.moveprev = function (callback) {
return instance.stop().to(instance.i - 1, callback);
};
}
return applyMethod.data(key, instance);
}
});
})(jQuery)
The key was to address the data attribute as sroes suggested.
Moreover i needed to apply the original method, since i need the old methods.

jquery plugin method ands callbacks

I have a basic plugin that populates an array within the plugin. How can I get that array via a method call with parameters. This is my first plugin so please go easy on me if this is a dumb question.
basic Plugin
(function($) {
$.fn.myPlugin = function() {
return this.each(function(){
tagArray = []; // my array that is populated
//code that does stuff to populate array
});
}
})(jQuery);
I would like to get the tagArray like so...
var arr = $('.className').myPlugin("getArray");
Where I can then use that array elsewhere. How can I accomplish this?
Thank you for any help.
I don't see why you would need the "getArray" parameter. In any case you need to define only 1 array and make your function return it:
(function($) {
$.fn.myPlugin = function() {
var tagArray = [];
this.each(function(){
// add something to tagArray
});
return tagArray;
}
})(jQuery);
That's a rather strange requirement, but an easy way to do that if there is only parameter would be something like :
(function($) {
$.fn.myPlugin = function(param) {
var tagArray = [],
elems = this.each(function(){
tagArray.push( $(this).text() ); // whatever you do ??
});
return param == 'getArray' ? tagArray : elems;
} // ^^ if the parameter is passed, return the array, otherwise the elems
})(jQuery);
FIDDLE
It's a bit hackish, but it works. You could also just return this.map(function() {... to always return an array etc, or read up on how to pass multiple parameters to a plugin and do different things etc. instead of the hardcoded check for 'getArray' used above.
Try
(function($) {
function Plugin($el, opts){
this.tagArray = [];
this.tagArray.push($el.attr('id')) //for testing the retuned instance
$el.data('myPlugin', this);
}
Plugin.prototype.getTagArray = function(){
return this.tagArray;
}
$.fn.myPlugin = function(opts) {
if($.type(opts) == 'string'){
var plugin = this.data('myPlugin');
return plugin[opts]();
}
return this.each(function(){
var $this = $(this);
new Plugin($this);
});
}
})(jQuery);
jQuery(function(){
$('#e1, #e2, #e3').myPlugin();
console.log($('#e1').myPlugin('getTagArray'))
console.log($('#e2').myPlugin('getTagArray'))
console.log($('#e3, #e1').myPlugin('getTagArray'))
})
Demo: Fiddle
I just finished writing a JQuery Plugin myself and here is the basic structure I settled on:
(function (window, document, $, undefined) {
//Local Methods
var methods = {
init : function(options){
//stuff you want to do when your plugin initializes i.e. when you do $('selector').myPlugin(options)
},
getArray: function(){
//your getArray method. Put your get array logic here
}
}
//Plugin Initialize
$.fn.myPlugin = function(args){
if ( methods[args] )
{
//execute JQuery Plugin Method
return methods[ args ].apply( this, Array.prototype.slice.call( arguments, 1 ));
}
else if ( typeof args === 'object' || ! args )
{
//Process JQuery Plugin Options
var opts = $.extend({}, $.fn.myPlugin.defaults, args);
var new_args = new Array(opts);
return methods.init.apply( this, new_args );
}
else
{
$.error( 'Method ' + args + ' does not exist on myPlugin' );
}
};
//Define Default Options
$.fn.myPlugin.defaults = {
option_1: '',
option_2: '',
option_n: ''
}
//API Methods
var M = $.myPlugin = function(){};
$.extend(M, {
getArray: function(){
return methods.getArray();
}
});
}(window, document, jQuery));
Doing this allows you to start your plugin like this (as usual):
$('.className').myPlugin(options);
and/or call your getArray function like this:
$.myPlugin.getArray();
I hope this helps you get closer to where you want to be.

jquery plugin that returns a new object

I'm creating my first jQuery plugin and want to create the jQuery object, but want to be able to control the object that was just created...
I'm building my plugin following the format recommended here: http://docs.jquery.com/Plugins/Authoring
Here is my test code:
(function($){
var $this = $(this);
var methods = {
init : function( options ) {
// methods.createDiv();
$this = $('<div>TEST CONTENT</div>')
.attr({ 'id':'test' })
.css({'color':'white','backgroundColor': 'red'})
.appendTo("body");
setTimeout(function(){
methods.green();
},
3000
);
return $this;
},
green : function( ) {
$this.css({'backgroundColor': 'green'});
},
blue : function( ) {
$this.css({'backgroundColor': 'blue'});
}
};
$.fn.myPlugin = function( method ) {
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.tooltip' );
}
};
})( jQuery );
$(document).ready(function () {
var myTest = $.fn.myPlugin();
myTest.blue();
});
Ultimately, I want to be able to control the newly created div using the myTest variable, but it's not working. I'm sure there are obvious pieces I'm missing and mistakes I'm making, but that's why I'm posting here. It's my first plugin, so if anyone could help me get this test code up and running I'd appreciate it. Currently, firebug report: "TypeError: myTest.blue is not a function"
Invoke your method as:
myTest.myPlugin("blue");
Here is a demo: http://jsfiddle.net/5p2Ba/
blue is not a method of the jQuery object here. You are only binding the methods object into a module using a closure.

Passing jQuery element data between methods?

I'm trying to create my first jQuery plugin, reading jQuery plugin authoring and one of the things it really emphasizes is to use methods instead of namespaces. I'm also trying to use the data from that guide to bounce variables between methods but it's not working. I need to create some data, pass it to another method to update it and send it somewhere else.
(function($) {
var methods = {
init : function(settings) {
return this.each(function(){
var x = 3;
var object = $(this);
// Bind variables to object
$.data(object, 'x', x);
$(object).bbslider('infoParse');
var y = $.data(object,'y');
alert(y);
}); // End object loop
}, // End init
infoParse : function() {
var object = $(this);
var x = $.data(object,'x');
alert(x);
var y = 10;
$.data(object,'y',y);
}, // End infoParse
}; // End method
$.fn.bbslider = function(method) {
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.bbslider' );
}
}; // End slider
})(jQuery);
Here's a jsFiddle to show what I mean: http://jsfiddle.net/wRxsX/3/
How do I pass variables between methods?
see if this http://jsfiddle.net/wRxsX/6/ is ok ?
element.data(k,v)
$.data should use on element
http://api.jquery.com/data/
Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.

Trying to learn jQuery plugin development

So I'm trying to learn how to implement method collection for a plugin based on this example: http://docs.jquery.com/Plugins/Authoring
What I cannot understand is how options that are extended with defaults for the plugin get sent to the individual methods.
I'm pretty sure any original options get sent to the method here:
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
So how can you extend these arguments with defaults? The example doesn't really define how to do this...
var methods = {
init : function( options ) {
return this.each(function(){
$(window).bind('resize.tooltip', methods.reposition);
});
}
}
Also, here is the code from the example plugin authoring page:
(function( $ ){
var methods = {
init : function( options ) {
return this.each(function(){
$(window).bind('resize.tooltip', methods.reposition);
});
},
destroy : function( ) {
return this.each(function(){
$(window).unbind('.tooltip');
})
},
reposition : function( ) { // ... },
show : function( ) { // ... },
hide : function( ) { // ... },
update : function( content ) { // ...}
};
$.fn.tooltip = function( method ) {
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.tooltip' );
}
};
})( jQuery );
Looks like my previous answer was closer to the mark than I previously thought.
Yes, this line is passing on the arguments:
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
Using .apply(), you can call a method, change its context (this value), and give it a collection of arguments instead of individual ones. Handy if you don't know how may arguments need to be passed on.
So you can break the above line down like this:
// reference the arguments passed to the plugin
var args = arguments;
// eliminate the first one, since we know that's just the name of the method
args = Array.prototype.slice.call( arguments, 1 )
// call the method that was passed,
// passing along the Array of the arguments (minus the first one),
return methods[method].apply( this, args);
// Note that it is being called from the context of "this" which is the jQuery object
So if the plugin was called like this:
$('.someElem').tooltip('destroy', 'someArg', 'anotherArg' );
The code will locate the "destroy" method, slice "destroy" off of the Arguments object, and call "destroy" passing along the Array of remaining arguments.
you use $.extend(existingObject || {} (new object), oneObject, secondObject, nthObject)
var mydefaults = { myDefaultArg : "foo" }
var inputOptions = { myDefaultArg : "Somethin else" }
var options = $.extend({}, mydefaults, inputOptions);
options.myDefaultArg == "Somethin else";
To access data, or to save them,you can use the data method
so if you are in the plugin, "this" is the jquery element element, you can now save data into it.
$(this).data("pluginname.somedataname", data);
and retriev it
var data = $(this).data("pluginname.somedataname");

Categories