In my project I create modules for each webpage and add to a base object called View:
App.js
var View = (function() {
var View = function() {
this.attributes = {
baseUrl : '',
urls : {}
};
};
View.prototype.setUrl = function(url) {
this.attributes.baseUrl = url;
};
View.prototype.getUrl = function() {
return this.attributes.baseUrl;
};
return new View();
})();
SearchView.js
var View = View || {};
var SearchView = View.SearchView = (function() {
var Private = {
search : function(url) {},
loadSearchResult : function() {},
clearSearchForm : function() {}
};
Private.search = function(url) {
ajax(url,...);
this.loadSearchResult();
};
var SearchView = function() {
this.settings = {};
};
SearchView.prototype.loadEventBindind = function() {
$(document)
.on('click','#search-button', function() {
Private.search(View.baseUrl);
})
.on('click','#reset-search', function() {
Private.clearSearchForm();
});
};
return new SearchView();
})();
search.html
<script type="text/javascript" src="media/scripts/Modules/App.js"></script>
<script type="text/javascript" src="media/scripts/View/SearchView.js"></script>
<script type="text/javascript">
View.setUrl('http://www.set.com/');
View.SearchView.loadEventBindings();
</script>
This code works properly in Chrome and Firefox, but throws an error in IE:
‘
View.SearchView‘ isnullor not an object
Does IE not support this way of creating objects?
There are few things you should do:
You have a weak point in that your App.js script could overwrite
Viewobject created by SearchView.js.If you’re sticking your guns to using View as class and namespace, make changes like this to prevent
Viewbeing overwritten.This script assumes that you are using jQuery (because of
$.extendmethod).