Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad that I'm tempted to structure a lot of my jQuery code as plugins?

Tags:

jquery

plugins

Since I learned how to write my own plugins in jQuery, I find I'm tempted to approach my javascript that way any time I'm building a page with any complexity to it. Obviously it's silly when we're talking about 10 lines of code, but when I'm going to be building a page with a couple hundred lines of javascript (or more), it seems the easiest way to:

  • Pass data (or even just options) from my PHP script into javascript -- $("#myform").myPagePlugin({options}, {data});
  • Gives me a "master" object in the DOM to attach my data to, instead of something hacky like global variables
  • Make my code re-usable later
  • "Plug in" my javascript to the page in a familiar way

Am I digging myself into a hole if I start doing this? Is there something I'm missing?

like image 559
keithjgrant Avatar asked Jan 13 '11 00:01

keithjgrant


1 Answers

My only critique would be that you're creating a jQuery plugin it seems you are never really planning on using again. This adds the overhead of running the JavaScript that jQuery runs to initialize a plugin when that overhead is not worth it, since the module will never be used again.

Instead of a jQuery plugin, why don't you create a JavaScipt object which is namespaced? For example:

var mypage = {};
mypage.controller = function(){

} //your preferred JavaScript object notation here.

Or is this namespaced approach what you are refering to as "hacky"? If so, I would respectfully disagree.

like image 84
Macy Abbey Avatar answered Dec 01 '22 17:12

Macy Abbey