Message: Object expected error in IE8 - javascript

I'm getting the object expected error in IE8. It's working good in chrome & FF.
Actually, error occurred on a javascript method.
for your reference,
function checkForm(idNum, varNum) { alert(234); }
//calling function here.
checkForm(idNum, varNum);
getting error in this line.
i have called this method in document.ready & select box onchange events.
Thanks.

I assume you are using jQuery if you are using document.ready? As in $(document).ready()
If you are then you want to give ready a function, not call a function
As in instead of having
$(document).ready(checkForm(idNum, varNum));
you would use
$(document).ready(function(){checkForm(idNum, varNum);});
ready is just a function and is expecting an object to be passed to it, just like checkForm a function is an object, just like a number or string, and can be passed to other functions and then called, like so...
function foo(bar){
bar();
}
function foobar(){
console.log("foobar has been called");
}
foobar();
foo(foobar);
The output of this being
"foobar has been called"
"foobar has been called"
If I understand what you are doing by the comments...

Related

how to create instances of a function in javascript?

Im trying to add an event listener to a object for example:
this.startLoading = function(){
this.a.addEventListener("complete", this.loadingHandler()); this gives me an error
},
this.loadingHandler = function(){
console.log("im doing something")
}
ERROR: "Uncaught Error: addListener only takes instances of
Function. The listener for event "complete" is "undefined"
However if I put the loadingHandler() function inside the scope it works, for example:
this.startLoading = function(){
var loadingHandler = function(){...}
this.a.addEventListener("complete", loadingHandler()); // this works
},
Im not sure what instances of a function means in that regard?
When you put () after a reference to a function, that means to call the function, and the value of the expression is whatever the function returns.
Your second example, that you say works, actually will not work, and you'll get the same error if the "startLoading" function is called.
Because you probably need to retain the proper context (this), what you probably need is
this.a.addEventListener("complete", this.loadingHandler.bind(this));
The .bind() method returns a function (exactly what addEventListener requires) that in turn will invoke your function such that this has the value requested.

Chrome not recognizing function arguments correctly

I have wrote some cross browser code for adding event listeners, then chrome started being funky, anyone know why this is happening?
Add Event listener code:
function addEventListener(Elm,Type,Func)
{
if(Elm.attachEvent)
Elm.attachEvent((Type.substr(0,2) == 'on' ? Type : 'on'+Type),Func);
else
Elm.addEventListener(Type,Func);
}
Code calling the method:
addEventListener(window,'load',SetSize);
addEventListener(window,'resize',SetSize);
Error:
Uncaught TypeError: Object load has no method 'addEventListener'
You can very clearly see that I have passed the arguments in the correct order yet they are not interpreted in said order..
You have overwritten window.addEventListener.
The native signature is: event_name, callback but yours is: object, event_name, callback.
Change the name of your function addEventListener or namespace it, like my_framework.addEventListener
You have redefined window.addEventListener. Anything you declare in the global namespace basically belongs to window, so:
function addEventListener(...) {
}
is the same as:
window.addEventListener = function(...) {
}
The argument signature for the native addEventListener is eventName, listener, but you have Elm, Type, Func.
Then inside your function body, you are doing Elm.addEventListener and passing it 'load' and SetSize. In that call, it calls your function again (because Elm is window) and this time, it attempts to call addEventListener on the string 'load', which won't work because a string doesn't have that method.
Change the name of your function, or namespace it, and it should work.
I would say the window object has not .attachEvent or .addEventListener.
This may caused because your function is named addEventListener and has overwritten the window.addEventListener()

Trying to call method name using string: Uncaught TypeError: Object [object global] has no method

So, I've figured out how to call a method in JavaScript when you have the method name in a string e.g. strCallback = 'targetMethod'; window[strCallback]();, however, I get the following error message indicating that it can't find the method and after researching I'm still not sure why.
Calling the method by the actual name works, but not by using window[strCallback]();
Error:
Uncaught TypeError: Object [object global] has no method 'targetMethod'
Code:
function startMethod(strCallback) {
var results = '...';
// window[strCallback](results); // <-- Causes error
targetMethod(results); // <-- Works
}
function targetMethod(r) {
console.debug(r);
}
startMethod('targetMethod');
Thanks for any help.
From the discussion in comments it looks like the problem is the context in which the callback method is declared. If you use window[callback] it expects the callback to me declared in the global context, in your case it does not appear to be the case. It might be because you have declared everything inside a anonymous function/dom ready creating a closure context for the function.
As a solution I would recommend not to pass the callback as a function name string, instead pass it as a function reference.
So instead of calling startMethod('targetMethod');, you need to call startMethod(targetMethod); and invoke callback using strCallback() instead of window[strCallback](results);.
I solution we worked out in the comments was just a workaround where we forced the callback to the global scope which is not a recommended method

Actionscript error when executing eventlistener in javascript

I have the following code using actionscript and the indesign sdk:
At the beginning of my Class
[ Embed (source= "resources/js/eventHandlers.jsx" , mimeType= "application/octet-stream" )]
private static var jsHandler:Class;
var jsxInterface:HostObject = HostObject.getRoot(HostObject.extensions[0]);
In my function:
jsxInterface.eval( new jsHandler().toString());
jsxInterface.init( this );
document.xmlElements.item(0).xmlElements.item("docpreset").importXML(File.applicationStorageDirectory.resolvePath("temp/cstyles.xml"));
jsxInterface.afterImport(document);
this is the code inside eventHandlers.jsx:
var asInterface = {};
function init(wrapper) {
asInterface = wrapper;
}
function afterImport(document) {
document.addEventListener (Document.AFTER_IMPORT, asInterface.test());
}
and from javascript I call this:
public function test():void {
trace("ole");
}
Now, the test function gets executed correctly, but after that the next thing that gets called is again this:
jsxInterface.afterImport(document);
and then an error is thrown:
Error: ActionScript error: Error: Missing required parameter 'handler' for method 'addEventListener'.
I have no idea anymore on what I need to do. All I want is for the xml to be imported and an event dispatched when the import is complete.
I have no idea why I even have to call a javascript function, and can't use the document.AFTER_IMPORT inside a normal eventListener. Can anyone help me out on this one please?
The problem seems to be that in your afterImport() method, you are adding the event listener incorrectly.
The second parameter to the addEventListener() method should be the name of a function (technically it's a reference to a function). In your code, you have put parentheses on the end of the function name -- so instead of providing the reference to the function, the function is being executed.
When the function executes, it returns nothing, so the second parameter to addEventListener() is missing and you get the error.
Try this instead:
function afterImport(document) {
document.addEventListener (Document.AFTER_IMPORT, asInterface.test);
// notice no "()" here ^^
}
[Edit]
Since you are still getting the error, you might want to add some code to debug it further.
In the method above, comment out the addEventListener line, and replace with something like this:
// for debugging
if (asInterface.test == null)
{
trace("fail: it's null");
}
else if (asInterface.test is Function)
{
trace("success: it's a function");
// this is the only code path where your error will not occur
}
else
{
trace("fail: i don't know what this is: ", asInterface.test);
}
I think you have to initiate the AS wrapper like this :
jsxInterface.init( this );
then the AS API becomes available to the js code.
Loic

Why is function() needed sometimes in JavaScript?

HTML
<button id='hello'>Click Me!</button>
JavaScript (wrong)
$('#hello').click(alert('Hello, World!'));
JavaScript (correct)
$('#hello').click(function() {
alert('Hello, World!');
}
I'm wondering why the first JS code triggers on the event load instead of click. Can anyone tell me why function() { [code] } is needed for the script to work properly?
In this example, I used jQuery events, but this is not specific to it, for example, I need to use it with setTimeout, too.
The click function expects another function as a parameter.
In the first case you would be passing the result of calling alert('hello world');, which is null.
The second is just a shorthand for:
$('#hello').click(callback);
function callback(){
alert('hello world');
}
Because .click() is a handler. The first argument is a function to assign. But if you actually pass the function with arguments then it will call the function (in this case alert) and then pass it's return value.
Writing $('#hello).click( function() { } )` is basically a short hand for writing:
var myfunction = function() {
// code
};
$('#hello').click( myfunction );
As you can see in the long hand way, it's passed as a reference to the function instead of the function's return value.
Your first example says "evaluate
alert('Hello, World!')
right now, and pass the result as an argument to click. "
The second says "Define a function which will do the alert when I call it, and pass that whole function as an argument to click.
The function() { ... } syntax is how you declare an anonymous function in Javascript. jQuery uses lots of these to specify that some action will be performed later, like when an event occurs. You can think of it as delaying the execution of your function until necessary. Without this syntax, whatever code you place there is evaluated immediately, which is not what you want for an event handler.
You might think, "why isn't JavaScript smart enough to know the difference?" Consider this:
function returnCallback(linkId, data) {
return function(e) {
alert('Clicked on ' + linkId + '. Here is some data: ' + data);
// Maybe do some stuff with e, the event parameter
}
}
$('#some-link').click(returnCallback('some-link', 'some-data'));
$('#other-link').click(returnCallback('other-link', 'different-data'));
This is a contrived example, but it illustrates the power of anonymous functions and closures. This works since returnCallback returns a function.
In the first instance, "JavaScript wrong", you're actually calling alert('Hello, World!') at the point that the script is loaded. Now, the reason you pass the .click function a function is because it can call it at any point. Essentially, you're packing code together to be run (or not run at all) at any point when you put it in a function.
$('#hello').click(alert('Hello, World!')); is attempting to run alert('...') and pass its return value to the .click() function which will not work as expected.
This is because JavaScript evaluates everything and during this process your alert is invoked. You can use anonymous function or you can also use your own custom function as implemented below:
<script language="javascript" type="text/javascript">
$("#mybutton").click(clickFired);
function clickFired() {
alert('click fired');
}
</script>
The parameter required for the .click() function is a Function. Therefore $("#hello").click(function { [code] }); is required. Because there's nothing to return by alert().
The click function here assigns a value to the event handler.
With the first ("wrong") code you're assigning a value of alert('Hello, World!') which is itself a function call, so it's going to be immediately evaluated and hence appear at load.
With the second ("correct") code you're now assigning a new anonymous function which is not executed itself, just instantiated at load. Hence this will work as expected later.
somefunction(alert('hello! world'));
this would mean you want to pass to somefunction the return value of alert("hello! world").
jquery click expects a callback that it should fire upon click on the element. so you put it in a function which does not execute unless someone (here jquery) calls it explicitly.

Categories