I was just asked to write a little news ticker script for one of our websites, so I re-wrote an existing jQuery script to fit our needs. Only afterwards I was told they use Prototype instead of jQuery, so now I have to convert the script.
Most of the simple parts I’ll be able to find out using the Prototype documentation, but there’s some parts in the jQuery that I’m not familiar with. I’m mainly talking about the parts like:
(function($) {
$.fn.newsTicker = $.fn.newsticker = function(delay)
{
delay = delay || 4000;
initTicker = function(el)
{
//bla bla some stuff
};
//here be more functions
this.each(
function()
{
if(this.nodeName.toLowerCase()!= "ul") return;
initTicker(this);
}
);
};
and
$.newsticker = $.newsTicker =
{
pause: function(el)
{
(el.jquery ? el[0] : el).pause = true;
},
//more functions
}
})(jQuery);
Are these some sort of classes? I don’t get how $(#element).newsTicker() fires the right function. How does this work, and more importantly what does it translate to in Prototype?
Full script: http://jsfiddle.net/PXn4r/9/
I cannot help you with the Prototype port but here’s how the original code works.
In jQuery you have a single global object, normally aliased as
$, that contains all the functions you can use (the “features”). These features are extensible: you can add your own function to the global object and if you do it properly it’ll be undistinguishable from any other jQuery built-in function. If you do it in a reusable style, you’ve written a plug-in. That’s what the code does:It creates a jQuery method that accepts a
delayparameter. (Actually, it’s defined twice so you can misspell the name.) You can now do stuff like this:Now this:
The
$alias is just a convention and can be available or not. This piece of code defines an unnamed function that receives thejQueryglobal object and stores it in a local variable called$. That way you can be sure that$exists and it doesn’t conflict with any other$variable that may be around.Update
jQuery.fnis a special object for plugins. I don’t know what happens if you add your function anywhere else (it may work as expected or not, I haven’t tested it) but that’s the best practice. You can consider it a namespace: stuff placed there won’t interfere with anything else.Reference: http://docs.jquery.com/Plugins/Authoring
BTW, a properly written plugin allows you to insert it in the middle of a jQuery chain, e.g.: