Lately, I've adopted a new approach of encapsulating my functions within Objects like this:
var Search = {
carSearch: function(color) {
},
peopleSearch: function(name) {
},
...
}
While this method greatly improves readability, the challenge I face is in maximizing reusability. I encounter difficulties in two main areas:
Handling parameters. Oftentimes, I have a search interface with multiple input fields and a button triggering the JavaScript search function. I find myself either cluttering the onclick event of the button to extract and format values from the input fields before passing them to the function, or hardcoding the HTML input field names/IDs for later retrieval via JavaScript. The workaround I currently use involves passing the field names/IDs as parameters to the function, which then fetches the values from the input fields. While effective, this approach feels somewhat inelegant.
Managing return values. Typically, JavaScript functions lead to direct visual changes on the screen or trigger other actions upon completion. However, when these screen-altering effects are placed at the end of a function, reusability becomes a challenge. For instance, after executing a search, displaying the results on the screen poses a dilemma.
I'm curious to know how others tackle these issues. Upon reflection, it dawned on me that perhaps I need a layer of page-specific JavaScript between my application's usage and the generic methods I create for universal application. Taking the earlier example, I might implement a search button whose onclick event calls a page-specific search function where the search field IDs/names are hardcoded, ultimately marshaling the parameters and invoking the generic search function. This generic function would solely handle data/objects/variables without directly manipulating the DOM. Subsequently, the page-specific search function could receive the data and make appropriate DOM alterations.
Am I steering towards the right direction, or is there a more efficient pattern to streamline the reuse of JavaScript objects/methods?