How to isolate my javascript code to prevent collisions?
I have been writing a lot of javascript functions and event listeners and I want to move them into their own namespaced, isolated place that doesn't conflict when I concatenate and minify it with my other javascript files.
I am still new to javascript, so there may be simple solution to this answer. I started by creating a javascript object:
var MySpecialStuff = {
init: function(){
//do everything here
}
};
Then in my html, on the page I want to use it on I can initialize this code:
<script>
MySpecialStuff.init();
</script>
But then the init
method started growing and I need to start breaking that code into smaller chunks, but I am stuck on the syntax and how to set private methods/variables and call them from within the init
method and other private methods. How can I do this?
Am I headed in the right direction? What other ways can I / should I go about doing this sort of thing?
You are headed in the right direction. You can use the module pattern to create an object with private members and methods like this:
var foo = function(){
var bar = ""; //private
function funk(){
//private function
return "stuff";
}
return{
getBar: function(){
return bar;
},
init: function(){
alert(funk());
},
randomMember: 0 //public member
}
}();
Only what's in the return block is public, but you can call any private methods/access any private methods from within the return block.
Thanks to Joseph for linking to another SO question which explained this approach:
Another way to do it, which I consider to be a little bit less restrictive than the object literal form:
var MySpecialStuff = new function() {
var privateFunction = function() {
};
this.init = function() {
};
};
I like to further segment my code into a more modular approach. So, let's say we have a page that has a list of blog posts, a page menu, and a sidebar. I'd end up with this:
var blog_controller = {
init: function(){
document.getElementById('some_element').addEvent('click', this.handleSomeClick);
this.applySomePlugin();
},
applySomePlugin: function () {
/* do whatever needs to happen */
},
handleSomeClick: function () {
// scope will be element
this.style.color = 'red';
}
};
var page_menu_controller = {
init: function(){
document.getElementById('some_other_element').addEvent('click', this.handleSomeClick);
},
handleSomeClick: function () {
// scope will be element
this.style.color = 'blue';
}
};
... and so on. This keeps code organized by purpose, helps keep scope clear, and allows you to reuse elements of code that might occur frequently (for instance, if you AJAX'd in a new blog post, you could call this.applySomePlugin
again).
This of course is a quick-and-dirty example, but I hope you get the idea
链接地址: http://www.djcxy.com/p/17072.html