I have some inherited JS code that uses this format:
function main(param) {
var myVar;
function doSomething() {
...
}
....
doSomething();
....
}
It works, but now I have to control some click events. Something like this:
function main(param) {
var myVar;
function manageEvent(item) {
...
myVar = item.value;
...
}
....
item.onclick = function() { manageEvent(this) }
....
}
The problem is that manageEvent() has no access to myVar and I don't know how to solve the problem without rewriting all the code (really hard work). How can I manage the event in order to give "manageEvent" access to myVar?
It works: http://jsfiddle.net/kgmYM/
Your problem is somewhere else, it certainly is not in this code; it's perfectly fine. Try and see if what you're clicking actually has the same value; try and play with its value and see the result. But anyway, your posted code works, and without any further information, we can't find what's really wrong in your situation.
Related
I want to be able to put the code in one place and call it from several different events.
Currently I have a selector and an event:
$("input[type='checkbox']").on('click', function () {
// code works here //
});
I use the same code elsewhere in the file, however using a different selector.
$(".product_table").on('change', '.edit_quantity', function () {
// code works here //
});
I have tried following the advice given elsewhere on StackOverflow, to simply give my function a name and then call the named function but that is not working for me. The code simply does not run.
$(".product_table").on('change', '.edit_quantity', function () {
calculateTotals() {
// code does not work //
}
});
So, I tried putting the code into it's own function separate from the event and call it inside the event, and that is not working for me as well.
calculateTotals() {
// code does not work //
}
So what am I doing wrong ?
You could pass your function as a variable.
You want to add listeners for events after the DOM has loaded, JQuery helps with $(document).ready(fn); (ref).
To fix your code:
$(document).ready(function() {
$("input[type='checkbox']").on('click', calculateTotalsEvent)
$(".product_table").on('change', '.edit_quantity', calculateTotalsEvent)
});
function calculateTotalsEvent(evt) {
//do something
alert('fired');
}
Update:
Vince asked:
This worked for me - thank you, however one question: you say, "pass your function as a variable" ... I don't see where you are doing this. Can you explain ? tks. – Vince
Response:
In JavaScript you can assign functions to variables.
You probably do this all the time when doing:
function hello() {
//
}
You define window.hello.
You are adding to Global Namespace.
JavaScript window object
This generally leads to ambiguous JavaScript architecture/spaghetti code.
I organise with a Namespace Structure.
A small example of this would be:
app.js
var app = {
controllers: {}
};
You are defining window.app (just a json object) with a key of controllers with a value of an object.
something-ctlr.js
app.controllers.somethingCtlr.eventName = function(evt) {
//evt.preventDefault?
//check origin of evt? switch? throw if no evt? test using instanceof?
alert('hi');
}
You are defining a new key on the previously defined app.controllers.somethingCtlrcalled eventName.
You can invoke the function with ();.
app.controllers.somethingCtlr.eventName();
This will go to the key in the object, and then invoke it.
You can pass the function as a variable like so.
anotherFunction(app.controllers.somethingCtlr.eventName);
You can then invoke it in the function like so
function anotherFunction(someFn) { someFn();}
The javascript files would be structured like so:
+-html
+-stylesheets
+-javascript-+
+-app-+
+-app.js
+-controllers-+
+-something-ctlr.js
Invoke via chrome developer tools with:
app.controllers.somethingCtlr.eventName();
You can pass it as a variable like so:
$(document).ready(function() {
$('button').click(app.controllers.somethingCtlr.eventName);
});
JQuery (ref).
I hope this helps,
Rhys
It looks like you were on the right track but had some incorrect syntax. No need for { } when calling a function. This code should behave properly once you add code inside of the calculateTotals function.
$(".product_table").on('change', '.edit_quantity', function () {
calculateTotals();
});
$("input[type='checkbox']").on('click',function() {
calculateTotals();
});
function calculateTotals() {
//your code...
}
You could just condense it all into a single function. The onchange event works for both the check box and the text input (no need for a click handler). And jQuery allows you to add multiple selectors.
$('input[type=checkbox], .product_table .edit_quantity').on('change', function() {
console.log('do some calculation...');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="product_table">
<input type="checkbox">
<input class="edit_quantity">
</div>
Below is the code that I used for multiple java scripts on a single button. But only any one is working when I disable the second one. Please let me know: how do I change my code to make it to work fine?
function invoke(but)
{
if(but==0)
{
function move(){
document.getElementById('tgt1').value =
document.getElementById('Allocation').value;
document.getElementById('Allocation').value="";
document.getElementById("Send").disabled=true;
}document.myform.action="Alloc_Insert.do";
}
else if(but==1)
{
document.myform.action="";
}
else if(but==2){ document.myform.action="WL_Verif.do";}
else if(but==3){ document.myform.action="Add_Query.do";}
document.myform.submit();
}
And the html is as below:
<input type="Submit" value="Allocate" id="Send" name="submit" onClick="invoke(0);move();"/><br/>
change the name of the button to something else than "submit"
To explain what happens:
When you assign the name-attribute "submit" to the button(or any other form-element), this element will be accessible via
document.myform.submit
but there is also the build-in method of a form: submit(), you also may access it by using
document.myform.submit
What happens now when you call document.myform.submit()
I'll write the code a little bit different, and you will see trouble:
document.myform['submit']()
Instead of accessing the built-in method, the code points first to the form-element, and then tries to execute the method. But a form-element is not a method, it all ends up in an error and the rest of the script(including the call of move() ) will not get executed.
It's the same with "reset", you never should use the name of a built-in property/method of the form-element as name for form-elements.
notice the 'move' function is not declared outside the 'invoke' function.
Then;
either wrap them in a self invoking function:
onclick="(function(){ invoke(0);move(); })();"
or attach event handlers (preferred usually)
div.attachEventListener('click', function () { ... }); // DOM 3
div.attachEvent('click', function () { ... }); // IE
Your functions are declared in a weird way. You're defining move inside of invoke, which I don't think you want. If you want to have two functions, put move outside of invoke, like this:
function move(){
document.getElementById('tgt1').value =
document.getElementById('Allocation').value;
document.getElementById('Allocation').value="";
document.getElementById("Send").disabled=true;
}
function invoke(but)
{
if(but==0)
{
move();
document.myform.action="Alloc_Insert.do";
}
else if(but==1)
{
document.myform.action="";
}
else if(but==2){ document.myform.action="WL_Verif.do";}
else if(but==3){ document.myform.action="Add_Query.do";}
document.myform.submit();
}
A note: it's generally not a good idea to use onClick in your HTML -- it's better to put that in your JavaScript.
I think the problem is the scope of the move() function. Try defining move outside of invoke.
function invoke (but) {
if(but==0) {
document.myform.action="Alloc_Insert.do";
// I don't know if you meant to call move() here or not
}
else if (but==2) { document.myform.action="WL_Verif.do"; }
else if (but==3) { document.myform.action="Add_Query.do"; }
document.myform.submit();
}
function move(){
document.getElementById('tgt1').value =
document.getElementById('Allocation').value;
document.getElementById('Allocation').value="";
document.getElementById("Send").disabled=true;
}
Also, properly formatting your code will do wonders to the legibility of it.
NOTE: Firefox seems to be quite happy to execute the onClick="invoke(0);move();" even if move is defined inside invoke. Chrome however won't execute move because it can't find it. So be sure to test your script in multiple browsers as well.
In trying to namespace my js/jquery code, I have come up against the following problem.
Basically, I used to write all my JS code in each html/php file, and I want to abstract that away to a single js file with namespaces.
So, in my html file I have:
<script type="text/javascript">
$(document).ready(productActions.init());
</script>
And in my js file I have:
var productActions = {
init: function() {
alert('initialsed');
$('#field_id').change(function() {
alert('ok!');
});
}
The productActions init function is definitely running, because I get the first alert (initialised). However, it seems that none of the jquery binding functions do anything at all. Stepping through the init function shows that the above change function is being registered, but actually changing the value in the field does absolutely nothing.
Am I missing something obvious here?
$(document).ready(productActions.init());
This code calls init() immediately and passes its return value to ready(...). (just like any other function call)
Instead, you can write
$(document).ready(productActions.init);
To pass the function itself. Howeverm this will call it with the wrong this; if you need this, write
$(document).ready(function() { productActions.init() });
I have an object defined using literal notation as follows (example code used). This is in an external script file.
if (RF == null) var RF = {};
RF.Example= {
onDoSomething: function () { alert('Original Definition');} ,
method1 : function(){ RF.Example.onDoSomething(); }
}
In my .aspx page I have the following ..
$(document).ready(function () {
RF.Example.onDoSomething = function(){ alert('New Definition'); };
RF.Example.method1();
});
When the page loads the document.ready is called but the alert('Original Definition'); is only ever shown. Can someone point me in the right direction. I basically want to redefine the onDoSomething function. Thanks, Ben.
Edit
Thanks for the comments, I can see that is working. Would it matter that method1 is actually calling another method that takes the onDoSomething() function as a callback parameter? e.g.
method1 : function(){
RF.Example2.callbackFunction(function() {RF.Example.onDoSomething();});
}
Your code as quoted should work (and does: http://jsbin.com/uguva4), so something other than what's in your question is causing this behavior. For instance, if you're using any kind of JavaScript compiler (like Closure) or minifier or something, the names may be being changed, which case you're adding a new onDoSomething when the old one has been renamed. Alternately, perhaps the alert is being triggered by something else, not what you think is triggering it. Or something else may have grabbed a reference to the old onDoSomething (elsewhere in the external script, perhaps) and be using it directly, like this: http://jsbin.com/uguva4/2.
Thanks for the response .. in the end the answer was unrelated to the code posted. Cheers for verifying I wasn't going bonkers.
My application has something like the following structure
window.object1;
window.object2;
$(document).ready(function() {
window.object1 = new type1object();
});
function type1object() {
//lots of code
this.property = 'property';
window.object2 = new type2object();
}
function type2object() {
//lots of code
this.property = new type3object();
}
function type3object() {
//lots of code
console.log(window.object1);
this.property = window.object1.property;
}
The problem is that whenever I try to access window.object1 from anywhere other than the document ready callback it comes back as undefined, this is even though when I inspect the DOM window.object1 is defined exactly as I expect it to be.
I've tried doing the same as above but using simple global variables instead (i.e. var object1 instead of window.object1) ... Tried declaring initial dummy values for object1 and object2 in various places... but run up against the same problem.
Does anyone know why I can't access my global variables globally?
You have to make sure you are evaluating window.object1 after initiating it.
That is, in your case, only after document.ready finished executing
If you look at this example below you can see that at click both are initialized.
<html>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
window.object1 = new type1object();
window.object2 = new type2object();
//console.log(window.object1);
});
$(document).click(function(){
console.log(window.object1);
console.log(window.object2);
});
function type1object() {
}
function type2object() {
}
</script>
Since you are not setting the value of window.object1 until you are inside the document ready function, you wont be able to access it until it has run.
Nothing in your code shows that you couldn't just remove that document ready call altogether. It is generally reserved for waiting for elements to load in the dom, which it doesn't seem like you are doing. If you somehow do have elements that need to be waited on inside of code that isn't there, just put your script at the bottom of the page, right above the tag. This will do the equivalent of document ready.
writing the code really stripped out made the answer fall out - I was creating something that referenced object1 during the construction of object1.
So I changed it to this, so that the object exists (though with no content) before anything tries to reference it:
window.object1;
window.object2;
$(document).ready(function() {
window.object1 = new type1object();
window.object1.construct();
});
function type1object() {
//lots of code
this.construct = function() {
this.property = 'property';
window.object2 = new type2object();
};
}
function type2object() {
//lots of code
this.property = new type3object();
}
function type3object() {
//lots of code
console.log(window.object1);
this.property = window.object1.property;
}