In jQuery, it has many of manipulation methods. If you have written an jQuery plugin, often it will require to put a generated content into a container which is specified in initialization process. For example:
$(selector).plugin_foobar({ container: $('#container') });
appendTo is most likely to be used for such task. The generated content is put into #container and it’s enough for most cases.
Although I haven’t seen any flexible design on insertion, but I think the following code may come in handy for me someday:
$(selector).plugin_foobar({ container: $('#container'), func: $.fn.prependTo });
As you can see the func is supplied with prependTo and you can expect the generated contain will be inserted before the contents in #container, not after. An implementation could look like:
// in plugin_foobar() var container = opt.container; var f = opt.func; var gen_content = $('<div>foobar</div>'); f.call(gen_content, container); // ==> gen_content.prependTo(container);
By using call, it enables the flexibility we need here. Given certain function and operating on the generated jQuery object.
Since a function is supplied, it does not have to be jQuery functions, you can even use it as a filter function. It’s very flexible of how you can use this kind of design.
Of course, you can use a string as option, values can be "before", "after", etc. You can use switch to manually call the corresponding function, but the code does not look clean as the design above.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.