ICR
ICR

Reputation: 14162

Interacting with jQuery plugin objects after their creation

I have a ticker which items are updated using polling. I have written a simple jQuery plugin for the ticker which is invoked like so:

$("#cont ul").ticker();

Which turns a ul into a ticker, scrolling through the li. To add new items I have to add lis to the ul, which works fine. However, the OO in me wishes I could have an addItem function on a ticker object. However, I don't want to lose the chainability that jQuery uses.

Is there some method which is more obvious than adding ul's to the list but that fit's with the jQuery way of doing things?

Upvotes: 2

Views: 1192

Answers (2)

Andrew Theken
Andrew Theken

Reputation: 3480

what you should do is extend the settings for your plugin:

jQuery.ticker = function(settings)
{
var settings = 
jQuery.extend(
{
action : 'create',
item : $(this)
}
,settings);

return $(this).each(function(){
if(settings.action =='create')
{
  //initialize ticker..
}
else if(settings.action == 'add')
{
  //add to ticker.
}
}//end each.
}//end plugin.

$('#ticker').ticker(); //this will initialize it, no problem.

var settings1 = { action : 'add', item : $(expr1) }
$('#ticker').ticker(settings1);//this will execute the "add" action.

Upvotes: 5

nickf
nickf

Reputation: 546143

jQuery isn't really an OO solution, so you're correct in saying that it's not really the "jQuery way". I've heard Prototype is all about OO, so you might want to look into that one day.

There's no reason you couldn't add another function to the jQuery object though:

$.fn.addTickerItem = function(contents) {
    this.append(
        $("<li></li>").html(contents);
    );
    return this;
};

..but you'd be slowly polluting the namespace.

Upvotes: 1

Related Questions