开发者

Reusing jQuery Code ?

I have some jQuery Code, which I am planning to use in many pages in my asp.net web form application.

Example: Create User using jQuery dialog box code.

In Asp.net we employ a user开发者_StackOverflow中文版 control to reuse the same piece of code over and over. Any ideas on how can I reuse jQuery code?


Typically you put the code in an external .js file and use <script src="my/path/to/jsfile.js" type="text/javascript"></script> in every page you are using the javascript in. (or you can place it in your master template).

(moved from comment due to the fact that this... is not a comment :P)


Typically, when I work with more complex applications there are a few common patterns I usually follow with my jQuery code. To handle the problem with scattered JavaScript code all over the code base I try to package as much as possible in jQuery plugins and put some effort into making them as generic as possible.

You can find a lot of tips on designing jQuery plugins from this NDC 2011 talk.

When designing more JavaScript framework like applications with less jQuery and more plain old JavaScript, I try to partition my code in different files by feature. I use a packaging tool like AjaxMin to merge and minify the framework into as single deliverable JavaScript-file.


I'm not sure I get it either: if you mean that your experience with jQuery is that it's run at document ready, it might just be the examples you've found. In that case, dotweb's comment provides the answer.

If you mean you're not sure how to get that code into other pages without dumping it into a script tag via copy/paste, Joseph has the answer.

For the sake of contributing something new, here's a fairly typical way of doing it which takes into account both of the above:

Create (and include, as per Joseph) one or more external JS files that constitute what you think of as the JS components of your application. "myApp.js" or whatever. Inside this file, you can use an object to store all of your functions (as per dotweb). This gives it a safe namespace and provides a quasi-global way to access functions and variables. Not actually 'global' in the document sense of the word, but within a scope that you can easily work with and call from anywhere else in your application. So, your contents might look something like:

var myApp = myApp || {}; // create a new empty object if that variable name is available

myApp.divHider = function() {
  $('div').hide();
}

myApp.backColor = function(color) {
  $('body').css('background', color);
}

// document ready function, which is where you might be accustomed to seeing scripts executed. Doesn't HAVE to be in this file; could be anywhere that makes sense

$(function() {
  myApp.divHider(); // hide all divs on document ready. Just a silly example
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜