I’m looking for feedback, suggestions on how to structure my java scripts better. I’ve made an attempt to move js code into their own files. It works but I wonder if this is the preferred way when it comes to scripts like the sample below? Is the revealing prototype pattern overkill, or not a good option for other reasons?
Portalen.Archive = function() {
};
Portalen.Archive.prototype = function () {
var options = {
minDate: new Date(2012, 0, 1),
changeMonth: true,
changeYear: true
};
var start = function () {
$("#StartDate").datepicker(options);
$("#EndDate").datepicker(options);
$("#searchButton").on("click", function() {
search();
});
};
var search = function() {
$.ajax({
url: "/Archive/Index",
type: "post",
data: $("#searchForm").serialize(),
success: function (response) {
$("#resultContainer").html(response);
}
});
};
return {
start: start
};
}();
And in the view I use it like this
<script type="text/javascript" src="~/Scripts/app/portalen-archive.js"></script>
<script type="text/javascript">
$(function () {
var s = new Portalen.Archive();
s.start();
})
</script>
JavaScript is not Java, where all entities should be represented with classes.
Therefore we’re using classes/prototypes in JavaScript only when we need to create multiple objects of current type.
So creating of class here is not necessary in my opinion. But though you can use regular JavaScript object as namespace.
Also I’d name this method rather
initthanstart, but it’s up to you of course.In module:
Somewhere else:
Additionaly I want to suggest you to take a look to Require.js which will allow you to organize your JavaScript modules in convenient way.