Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which strategy makes more sense in this jQuery plugin? [closed]

I'm making a jQuery plugin that displays alerts on the page. The plugin itself inserts the alert markup into the DOM. Since the jQuery way is to make everything return this to maintain chaining, I've run into an interesting issue I'd like feedback on. I'm trying to decide between the following two options.

Option One:

$("#content").alert('prepend', {type:'error', message:'This is an error'})

This looks pretty simple. An alert is prepended to the beginning of the #content DOM element. The problem is that it's unclear what is returned. It would make sense to return the alert element that was just created, but that kind of goes against the jQuery way.

Option Two:

$("<div>").alert({type:'error', message:'This is an error'}).prependTo("#content")

This way seems less clear and less intuitive, but it's more inline with the jQuery way of doing things, and it's clear what element is going to be returned.

So which options would you choose? My concern is that most users may not know that you can do $('<div>') to create a new element. On the other hand, I don't know of any well-known projects whose jQuery plugin methods return elements other than the elements they're invoked on, but perhaps there are. Thoughts?

like image 388
Philip Walton Avatar asked Nov 13 '22 05:11

Philip Walton


1 Answers

I would just put it in the jQuery namespace (instead of on its prototype):

$.alert({type:'error', message:'This is an error'}).prependTo("#content");

In addition, you might consider asking for a selector/DOM node/jQuery object, instead of having the user prepend it themselves:

$.alert({
    parent: '#content', // or $('#content') or document.getElementById('content')
    type: 'error',
    message: 'This is an error'
});
like image 187
Joseph Silber Avatar answered Nov 16 '22 03:11

Joseph Silber