I'm testing a js function that uses functions from other js files.
One of my external js files has a function defined as such:
functionname.functionextension = function () {.....}
when testing using jasmine, and calling functionname.functionextension, it complains that functionname is not defined. I think it believes that functionname is an object..
I know that one way to get around this is to modify the function name but I can't do that. Is there any other way?
Thanks
In javascript, all functions are objects. In the external js file, the function is probably defined like this:
var functionname = functionname || {};
functionname.functionextension = function () {
...
};
If you're getting a script error that functionname is not defined, there is either an error in the external javascript or you are not calling some initialization function that the external script requires to set up its objects.
It worked for me...u need to call function by its full name like functionname.functionextension() while calling.
Related
I need to customize the behavior of a function in product.js under /_core/js. The function declaration is:
function replaceAddToCartSections(data) {}
I tried by creating a function with the same name in custom.js. Since this one is the last js file loaded in the HTML, I thought the original function would be overriden, but that wasn't the result.
When I print replaceAddToCartSections.toString() in Mozilla dev tools, I get my new function. However, when I remove the function from custom.js, I get :
ReferenceError: replaceAddToCartSections is not defined
Are the functions of core.js private? How to override them? Is is something relative to Webpack configuration?
Just after replaceAddToCartSections is called, updatedProduct is emitted, so you can define a function like:
prestashop.on('updatedProduct', function (event) {
// your code
})
I am using Meteor JS.
I have a JavaScript function defined in file A which I want to reuse by calling from file B. Example:
File A:
function Storeclass(){}
Storeclass.validate=function(){...}
From A JavaScript I try to call StoreClass.validateBasic() it works but the same call doesn't work from B. Also I tried in B doing var storeClassObj=new StoreClass(); and storeClassObj.validate(). I get error ReferenceError: StoreClass is not defined.
Read this doc about namespacing in Meteor.
The relevant portion is this:
// File Scope. This variable will be visible only inside this
// one file. Other files in this app or package won't see it.
var alicePerson = {name: "alice"};
// Package Scope. This variable is visible to every file inside
// of this package or app. The difference is that 'var' is
// omitted.
bobPerson = {name: "bob"};
However, later on in the same doc, it says this:
When declaring functions, keep in mind that function x () {} is just shorthand for var x = function x () {} in JavaScript.
This suggests that the function you have written is private to the file A and cannot be accessed from file B, even if load order is correct!
Because your function in file B might invoke before File A is ready so you have to make sure that all required js files are loaded successfully.
If you are using jQuery then in file B call your function in document ready function:
$( document ).ready(function() {
//File A code
});
or in plain JavaScript:
(function() {
// your page initialization code here
// file A code
})();
I'm still getting to grips with some of the JavaScript variable handling and I'm a bit confused over this.
I have a variable declared in a file like this:
(function (myControls, $, undefined) {
var selectedLifeArea;
...
But when looking for these in Firebug they aren't listed under the myControls "namespace" as I expected, only the functions are listed. Why is that?
Your code is wrapped in it's own scope.
Try adding some breaks in the js debugger, then you can read the variables.
Here is a brief description:
var globalVariable;
(function () {
var localVariable;
// can access both `globalVariable` and `localVariable`
...
)();
// can only access `globalVariable`
Someone on the RubyRogues podcast once said "Learn CoffeeScript because CoffeeScript writes better javascript than you do." Sorry, can't remember who said it...
So, I took a very simple WORKING javascript function:
togglingii.js
function pdtogglejs(id) { $('div .partybackground').removeClass("hidden"); }
Which is being called by this line:
Read More...
Then I converted it into this coffeescript:
toggling.js.coffee
pdtogglecs(id) ->
jQuery('div .partybackground').removeClass("hidden")
and changed the html to reference the pdtoggle*c*s instead of pdtoggle*j*s.
I can see BOTH of them just fine in my application.js file:
(function() {
pdtogglecs(id)(function() {
return jQuery('div .partybackground').removeClass("hidden");
});
}).call(this);
function pdtogglejs(id) { $('div .partybackground').removeClass("hidden"); }
;
(function() {
}).call(this);
However, only the pure javascript works. The coffeescript always returns Uncaught ReferenceError: pdtogglecs is not defined.
Based on other stackoverflow questions it must be some sort of namespace error. Probably because of the way pdtogglecs is, itself, inside of a function?? However, I have tried defining the coffeescript function with: window.pdtogglecs, this.pdtogglecs, root.pdtogglecs and the coffescript one always fails with that error.
What am I missing??
Thanks!!
You have two problems, one is a bit of CoffeeScript syntax confusion and the other is the namespace problem that you know about.
We'll start by sorting out your syntax confusion. This:
f(x) -> ...
is interpreted like this:
f(x)(-> ...)
So when given this:
pdtogglecs(id) ->
jQuery('div .partybackground').removeClass("hidden")
CoffeeScript thinks you're trying to call pdtogglecs as a function with id as an argument. Then it thinks that pdtogglecs(id) returns a function and you want to call that function with your -> jQuery(...) function as an argument. So it ends up sort of like this:
callback = -> jQuery(...)
returned_function = pdtogglecs(id)
returned_function(callback)
And that's nothing like your original JavaScript. You want to create a function named pdtogglecs which takes id as an argument and then runs your jQuery stuff:
pdtogglecs = (id) ->
# -----^ this is sort of important
jQuery('div .partybackground').removeClass("hidden")
You can see what's going on by looking at the generated JavaScript.
The namespace problem is easy and you can probably figure that out based on the other question you found. However, I'll take care of it right here for completeness.
CoffeeScript wraps each .coffee file in a self-executing function to avoid polluting the global namespace:
(function() {
// JavaScript version of your CoffeeScript goes here...
})();
That wrapper makes everything scoped to the .coffee file. If you want to pollute the global namespace then you have to say so:
window.pdtogglecs = (id) -> ...
You can also say:
#pdtogglecs = (id) -> ...
but I prefer the explicitness of directly referencing window, that also saves you from worrying about what # (AKA this) is when you're code is parsed.
I'd like to write Javascript scripts for Google Apps Script using CoffeeScript, and I'm having trouble generating functions in the expected form.
Google Apps Script expects a script to contain top-level, named functions. (I may be using the wrong terminology, so I'll illustrate what I mean with examples...)
For example, this function is happily recognised by Google Apps Script:
function triggerableFunction() {
// ...
}
... while this function is not (it will parse, but won't you won't be able to trigger it):
var nonTriggerableFunction;
nonTriggerableFunction = function() {
// ...
};
I've found that with CoffeeScript, the closest I'm able to get is the nonTriggerableFunction form above. What's the best approach to generating a named function like triggerableFunction above?
I'm already using the 'bare' option (the -b switch), to compile
without the top-level function safety wrapper.
The one project I've found on the web which combines CoffeeScript and Google App Script is Gmail GTD Bot, which appears to do this using a combination of back-ticks, and by asking the user to manually remove some lines from the resulting code. (See the end of the script, and the 'Installation' section of the README). I'm hoping for a simpler and cleaner solution.
CoffeeScript does not allow you to create anything in the global namespace implicitly; but, you can do this by directly specifying the global namespace.
window.someFunc = (someParam) ->
alert(someParam)
Turns out this can be done using a single line of embedded Javascript for each function.
E.g. this CoffeeScript:
myNonTriggerableFunction = ->
Logger.log("Hello World!")
`function myTriggerableFunction() { myNonTriggerableFunction(); }`
... will produce this JavaScript, when invoking the coffee compiler with the 'bare' option (the -b switch):
var myNonTriggerableFunction;
myNonTriggerableFunction = function() {
return Logger.log("Hello World!");
};
function myTriggerableFunction() { myNonTriggerableFunction(); };
With the example above, Google Apps Script is able to trigger myTriggerableFunction directly.
This should give you a global named function (yes, it's a little hacky, but far less that using backticks):
# wrap in a self invoking function to capture global context
do ->
# use a class to create named function
class #triggerableFunction
# the constructor is invoked at instantiation, this should be the function body
constructor: (arg1, arg2) ->
# whatever
juste use # in script, exemple of my code :
#isArray = (o)->
Array.isArray(o)
it will be compiled in :
(function() {
this.isArray = function(o) {
return Array.isArray(o);
};
}).call(this);
this = window in this case, so it's global function