How can change this Javascript to not use global variables?
I'm having some trouble working out how to control program flow and not use global variables with the Javascript in my web app. In this example, when get_notes()
is called, the ids of the received notes are stored in the current_note_ids
array. When add_to_discussion()
is called, current_note_ids
is sent as a parameter to the server request. How can I do this without having current_note_ids
as a global variable?
<script type="text/javascript">
var current_note_ids = [];
function add_to_discussion(){
$.post('/add_to_discussion',{cu开发者_C百科rrent_note_ids:current_note_ids});
}
function get_notes(){
$.post('/get_note_combination',{}, function(data) {
current_note_ids = []; // clear existing note details
for (i in data.notes) {
current_note_ids.push(data.notes[i].guid);
}
}
}
$(document).ready(function() {
$('#add_to_discussion_button').click(function(){
add_to_discussion();
return false;
});
$('#get_notes_link').click(function(){
get_notes();
return false;
});
});
</script>
This removes all that code from the global scope using a closure
(function () {
var current_note_ids = [];
function add_to_discussion(){
$.post('/add_to_discussion',{current_note_ids:current_note_ids});
}
function get_notes(){
$.post('/get_note_combination',{}, function(data) {
current_note_ids = []; // clear existing note details
for (i in data.notes) {
current_note_ids.push(data.notes[i].guid);
}
}
}
$(document).ready(function() {
$('#add_to_discussion_button').click(function(){
add_to_discussion();
return false;
});
$('#get_notes_link').click(function(){
get_notes();
return false;
});
});
})();
You can use anonymous function to make it OO-like. In this case, you can choose what to "expose".
var notes = $(function() {
var current_note_ids = [];
function add_to_discussion() {
$.post('/add_to_discussion', {
current_note_ids: current_note_ids
});
}
function get_notes() {
$.post('/get_note_combination', {}, function(data) {
current_note_ids = []; // clear existing note details
for (i in data.notes) {
current_note_ids.push(data.notes[i].guid);
}
})
}
return {
add_to_discussion: add_to_discussion,
get_notes: get_notes
};
})();
$(document).ready(function() {
$('#add_to_discussion_button').click(function() {
notes.add_to_discussion();
return false;
});
$('#get_notes_link').click(function() {
notes.get_notes();
return false;
});
});
精彩评论