简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM