I've been happily using jQuery, creating vars and binding events in my modules (which have only a little bit of JS). But recently I needed to add an anonymous functions to my code and after investigating some more, I learned about modular patterns and encapsulation.
So what I'm trying to teach myself is to write clean, fast and maintainable JavaScript code in object-oriented fashion (as opposed to "functional" jQuery code before).
My module inserts a search box (input) that uses Ajax and displays drop-down results.
What I want to have is a template file with the search box other necessary elements; Then the most flexible way would be to pass the elements to the code in JavaScript file - I could easily adjust settings in the same file if I decide to change IDs or the elements.
Then there should be a separate file with the actual code; It should make no presumptions about the elements of the page.
I follow this article:
http://esbueno.noahstokes.com/post/77292606977/self-executing-anonymous-functions-or-how-to-write
These are my thoughts and what I would like to know:
- Is this structure written correctly to accomplishing this task?
- Is the anonymous function (self-executing one) being used correctly here?
- Is there anything to be optimized (maybe I'm "overkilling" something)?
- Is
$.proxy
used correctly? - I to use an object to defined methods, however, I cant think of a way to only expose a public method. Is writing non-objective (simple enclosed vars and functions) the way to go?
search_box.tpl
<script type="text/javascript" src="autosearch.js"></script>
<form>
<input id="search-1" type="search">
</form>
<script type="text/javascript">
AutoSearch.init({
input : $('#search-1'),
option2: ''
});
</script>
autosearch.js
var AutoSearch = (function($) {
var search = {
cache: {},
bindEvents: function(){
this.input.on('keyup', $.proxy(this.processInput, this));
},
processInput: function(){ alert(this.input.val()); },
init: function(options) {
this.input = options.input;
this.bindEvents();
}
}
return search;
})(jQuery);