How can change this Javascript to not use global variables? - javascript

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',{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;
});
});
</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;
});
});

Related

Javascript: repeat function

I have a function with if inside. In case if returns false I need repeat function again
this.reloadComment = function () {
var previous_comment = self.Comment();
$.getJSON(Routes.my_service_search_path(self.ID), {}, function (data) {
if (data.Comment.ID != previous_comment.ID) {
self.Comment(data.Comment);
} else {
// repeat
}
});
};
If self within the function is what this is outside it, then simply:
} else {
// repeat
self.reloadComment();
}
If not, use a named function; then since you have that nice name you can use, call it when you need to repeat it:
function reloadComment() {
var previous_comment = self.Comment();
$.getJSON(Routes.my_service_search_path(self.ID), {}, function (data) {
if (data.Comment.ID != previous_comment.ID) {
self.Comment(data.Comment);
} else {
// repeat
reloadComment();
}
});
}
this.reloadComment = reloadComment;
If you don't need to support IE8, you can do that with a single named function expression:
this.reloadComment = function reloadComment() {
var previous_comment = self.Comment();
$.getJSON(Routes.my_service_search_path(self.ID), {}, function (data) {
if (data.Comment.ID != previous_comment.ID) {
self.Comment(data.Comment);
} else {
// repeat
reloadComment();
}
});
};
...but on IE8 (and earlier) you'd end up with two copies of that function, not one; if you do that a lot, it ends up being wasteful. (It wouldn't make any other difference in this particular case, though; it'd still work. There are other situations where it would make a difference, so I stay away from NFEs entirely in code that needs to deal with IE8.)
Try This
this.reloadComment = function () {
var me = this;
var previous_comment = self.Comment();
$.getJSON(Routes.my_service_search_path(self.ID), {}, function (data) {
if (data.Comment.ID != previous_comment.ID) {
self.Comment(data.Comment);
} else {
me.reloadComment();
}
});
};

call function before plugin function starts

I have a function to find highest value in an XML file from certain tag which has to assign one of default value in plugin. My problem is my plugin code runs before the other function hence a null value is returned. Can I run function get_Highest_Property_Prise() before plugin, like java constructor? Or some how initialize a global variable before plugin code kicks in?
var pulgin_Global_Variables = {
hight_price: ""
};
(function($) {
$.fn.SearchProperty = function (options) {
var defaults = {
S_MinPrice: 0,
S_MaxPrice: get_Highest_Property_Prise()
};
alert("yo yo "+defaults.S_MaxPrice);
}
})(jQuery);
function get_Highest_Property_Prise()
{
$.get('Data.xml', function (XML_property) {
$(XML_property).find('property').each(function () {
var c_Price = parseInt($(this).find('priceask').text().replace(',', ''));
if (c_Price > pulgin_Global_Variables.hight_price) {
pulgin_Global_Variables.hight_price = c_Price;
}
}); //end of function
});
}
var pulgin_Global_Variables = {
hight_price: ""
};
$.fn.SearchProperty = function (options) {
var defaults = {
S_MinPrice: 0,
S_MaxPrice: pulgin_Global_Variables.hight_price
};
alert("yo yo "+defaults.S_MaxPrice);
}
})(jQuery);
//here set max price to match your global object
$.get('Data.xml', function (XML_property) {
$(XML_property).find('property').each(function () {
var c_Price = parseInt($(this).find('priceask').text().replace(',', ''));
if (c_Price > pulgin_Global_Variables.hight_price) {
pulgin_Global_Variables.hight_price = c_Price;
}
}); //end of function
}).done(function () {
$(whatever).SearchProperty()
})

JavaScript refer to a method inside a method?

Ok, just solved one problem where this refered to the wrong scope. Now I have another problem.
So I want to call a method that is inside a method. But I do not know how, check this source:
function someObj() {
var self = this;
this.someMethod1 = function() {
var elementBtn = document.getElementById('myBtn');
elementBtn.onclick = function() {
self.someMethod2.methodMethod();
//I want this.someMethod2.methodMethod() to be called
//...but I get an big error instead. Is it even possible?
//this.someMethod2() works fine.
};
};
this.someMethod2 = function() {
this.methodMethod = function() {
alert('THIS IS THE ONE I WANTED!');
};
alert('NO, NOT THIS!');
};
}
Error msg:
Uncaught TypeError: Object function () { ...
With your code, someMethod2 would need to execute first for the function expression to be assigned. Even then, it would be assigned to the parent instance.
Bearing in mind that all functions are objects in JavaScript, this is what you want instead:
this.someMethod2 = function() {
alert('NO, NOT THIS!');
};
this.someMethod2.methodMethod = function() {
alert('THIS IS THE ONE I WANTED!');
};
You are trying to use an object accessor on a function. If you want it to work in this way, you need to return an object literal from your call to the "outer" function.
this.someMethod2 = function() {
return {
methodMethod: function() {
alert('THIS IS THE ONE I WANTED!');
}
}
};
You can then chain the call. self.someMethod2().methodMethod();
While this is not directly possible, you can pass a "command" to the outer function to tell it to execute the inner function. But, are you sure this is what you really need? Perhaps you should use objects instead of functions here. But here's the "command" way:
this.someMethod2 = function(cmd) {
var methodMethod = function() {
alert('THIS IS THE ONE I WANTED!');
};
if (cmd === "methodMethod") {
methodMethod();
return;
}
alert('NO, NOT THIS!');
};
function someObj() {
var self = this;
this.someMethod1 = function () {
var elementBtn = document.getElementById('myBtn');
elementBtn.onclick = function () {
self.someMethod2().methodMethod();
};
};
this.someMethod2 = function () {
this.methodMethod = function () {
alert('THIS IS THE ONE I WANTED!');
};
//return this for chain method.
return this;
};
}
trying
function someObj() {
var self = this;
this.someMethod1 = function() {
var elementBtn = document.getElementById('myBtn');
elementBtn.onclick = function() {
self.someMethod2().methodMethod();
};
this.someMethod2 = function() {
this.methodMethod = function() {
alert('THIS IS THE ONE I WANTED!');
};
alert('NO, NOT THIS!');
return this;
};
}
Also if you use prototype then
function someObj() {
var self = this;
this.someMethod1 = function() {
var elementBtn = document.getElementById('myBtn');
elementBtn.onclick = function() {
self.someMethod2.methodMethod();//['methodMethod']();
};
};
this.someMethod2 = function() {
};
this.someMethod2.methodMethod = function() {
alert('THIS IS THE ONE I WANTED!');
};
};
But the method methodMethod is static

I have no idea how to test this with Qunit?

I want to test this function:
/js/lib/front.js
var Front = function(){
this.onSignUp = function(){
if (!Form.assertInput("email")) {
$("input[name=email]").focus();
this.showHiddenMessage("Email not set.");
return false;
}
}
}
I have in:
/js/lib/form.js
function Form() {
this.assertInput = function (name, defaultValue) {
var text = $("input[name=" + name + "]").val();
if (defaultValue != null) {
if (defaultValue && text == defaultValue)
return false;
}
if(this.trim(text)) return true;
return false;
}
}
This simple test passing:
test("Front", function() {
var front = new Front()
ok(front);
});
But if I write something like this:
test("On Sign Up ", function() {
var front = new Front()
equal(front.onSignUp(),false,"passing test");
});
I have error:
Died on test #1: Form.assertInput is not a function
I don't understand, what I need test in function like this and how include function inside another function?
I've saved a working fiddle here. As a side note, you might want to check out a tutorial on using qUnit, here.One thing that you need to pay attention to is when you're declaring your functions. It's saying Form.assertInput is not a function because you can't access it like that. You need to use the this keyword, which refers to current context. The code should be something like this:
var Form = function () {
//good to have assertInput first if you're using it in a later function
this.assertInput = function (name, defaultValue) {
var text = $("input[name=" + name + "]").val();
if (defaultValue != null) {
//safer to explicitly close your if statements with {}
if (defaultValue && text == defaultValue) {
return false;
}
}
if ($.trim(text)) { return true; }
return false;
};
this.showHiddenMessage = function (message) {
alert(message);
};
this.onSignUp = function() {
//this will point to the current context, in this case it will be Form class
if (!this.assertInput("email")) {
$("input[name=email]").focus();
this.showHiddenMessage("Email not set.");
return false;
}
};
};
Also in the example code that you gave you're missing the Front class. So I created a dummy one in my fiddle like this:
var Front = function() {};
Here are the tests that were run:
$(document).ready(function() {
test("Front", function() {
var front = new Front();
ok(front);
});
test("On Sign Up ", function() {
var form = new Form();
equal(form.onSignUp(), false, "passing test");
});
});

Resolve function pointer in $(document).ready(function(){}); by json string name

I have a json object retrieved from server in my $(document).ready(...); that has an string that I would like to resolve to a function also defined within $(document).ready(...); so, for example:
$(document).ready(function{
$.getJSON(/*blah*/,function(data){/*more blah*/});
function doAdd(left,right) {
return left+right;
}
function doSub(left,right) {
return left-right;
}
});
with json string:
{"doAdd":{"left":10,"right":20}}
One way I thought about was creating an associative array of the function before loading the json:
var assocArray=...;
assocArray['doAdd'] = doAdd;
assocArray['doSub'] = doSub;
Using eval or window[](); are no good as the function may not be called for some time, basically I want to link/resolve but not execute yet.
Change your JSON to
{method: "doAdd", parameters : {"left":10,"right":20}}
Then do
var method = eval(json.method);
// This doesn't call it. Just gets the pointer
Or (haven't tried this)
var method = this[json.method]
How about something like this?
$(function(){
// Function to be called at later date
var ressolvedFunc = null;
// Ajax call
$.getJSON(/*blah*/,function(data){
// Generate one function from another
ressolvedFunc = (function(data) {
var innerFunc;
var left = data.left;
var right = data.right;
// Detect action
for (action in data) {
if (action == "doAdd")
innerFunc = function() {
return left + right;
};
else
innerFunc = function() {
return left - right;
};
}
return innerFunc;
})(data);
});
});
The anonymous function returns fresh function, with the new values stored within the enclosure. This should allow you to call the function at later date with the data previously retrieved from the GET request.
Rich
try this:
var doX = (function() {
var
data = [],
getDo = function(action) {
for(var d in data) {
if (data[d][action]) {
return data[d];
}
}
return null;
};
return {
set: function(sdata) {
data.push(sdata);
},
doAdd: function() {
var add = getDo("doAdd");
if (!add)
return 0;
return add.doAdd.left + add.doAdd.right;
},
doSub: function() {
var sub = getDo("doSub");
if (!sub)
return 0;
return sub.doAdd.left + sub.doAdd.right;
}
};
})();
$(document).ready(function{
$.getJSON(/*blah*/,function(data){ doX.set(data); });
});

Categories