var defaults = {
button: '#buttonId',
form: '#formId',
target: '#targetId',
url: '/change/me',
page: '/change/me/too',
};
clickToLoad = function( options ) {
var o = $.extend({},defaults,options);
$(o.button).live('click',function(){
$.ajax({
type: 'post',
url: o.url,
data: $(o.form).serialize(),
cache: false,
success: function(){$(o.target).load(o.page)},
error: function(){alert('data');}, // is this really what you want?
});
return false;
});
})(jQuery);
Here's how you would use it:
clickToLoad({
button: '#theButton',
form: '#theForm',
target: '#theDiv',
url: '/path/to/data/handler',
page: '/page/to/load',
});
It's a little bit better than copy/paste/tweak. Also, by standardizing your pages so they always use the same button ID or form ID or target ID, you could put that standard ID in the defaults section. Then, on a page where it uses the defaults, you can leave those parameters out of the call.
This, of course, pollutes the global namespace. You probably should define a namespace and put it there. But that is your choice.
Also, re-think your use of .live(). Are you adding and removing buttons that match that criteria during the life of the page? If not, you don't need to use .live(). You can, obviously, but should you?
I've got a lot of hard coded values in JQuery functions like the one below
$("#getTOByWeek").live("click", function(){
$.ajax({
type:"post",
url:"webapps/hr/admin/actions/act_adminHR_Handler.cfm",
data:$("#toByWeek").serialize(),
cache:"false",
success: function(){
$("#content-box").load("webapps/hr/admin/display/dsp_TOList.cfm");
},
error: function(){
alert("data");
}
});
return false;
});
I use this chunk of code repeatedly, changing the button name, form name, url loading div name, and the page that's loaded
(#getTOByWeek, /hr/admin/actions/act_adminHR_Handler.cfm, #toByWeek, #content-box, /hr/admin/display/dsp_TOList.cfm respectively in this case)
What I'd like to be able to do is have one code chunk that I throw variables at, instead of cutting/pasting and changing the hard coded values it would be much more elegant and make troubleshooting a lot easier. Not to mention making my .js file a helluva lot smaller.
Any thoughts on how to do this?
Thanks
sas
--
Scott Stewart
IT Consultant/ColdFusion Developer
4405 Oakshyre Way
Raleigh, NC 27616
(919) 874-6229
--
John Arrowwood
John (at) Irie (dash) Inc (dot) com
John (at) Arrowwood Photography (dot) com
John (at) Hanlons Razor (dot) com
--
http://www.irie-inc.com/
http://arrowwood.blogspot.com/
No comments:
Post a Comment