I’m working with some code like this (simplified):
var $form = $('form')
var els = {
radio: $form.find('input[type=radio]'),
check: $form.find('input[type=checkbox]')
}
The form in question may contain dynamically added inputs, but the els object is static when it’s defined, if the form gets new inputs, radio and check won’t change. I need to use els often throughout the code so I came up with this simple solution:
var getEls = function () {
return {
radio: $form.find('input[type=radio]'),
check: $form.find('input[type=checkbox]')
}
}
var foo = function () {
var els = getEls()
// do something with `els`
}
This works fine but I’m thinking this might not give the best performance since it has to query ALL elements again each time. Is there a better way to do this?
If you don’t call
getEls()in a loop or something performance should be fine. However, since you control the adding of elements to your form you have a few methods to streamline your code.Use a property
Use a data property on your form to save the number of particular elements so you can compare it with your saved number of elements before doing a complete refresh.
Update the collection
While you’re adding the object to the dom, you could as well add it to the saved set.