Javascript function file parameter - javascript

I'm trying to write a JS function that gets always the same file as parameter, like this:
function something(../content/id.csv){
//do something with this file
}
Is there a way to do it, without <file> input HTML tags?
Thanks for your help!

(Suggestion) Remove that param and use a local variable within that function.
But, if you want to call the function as follow something() and always will be that way, you can do this:
function something(path = '../content/id.csv'){
console.log(path);
}
something();
Resource
Default parameters

Related

Razor Syntax in External Javascript

So as you might know, Razor Syntax in ASP.NET MVC does not work in external JavaScript files.
My current solution is to put the Razor Syntax in a a global variable and set the value of that variable from the mvc view that is making use of that .js file.
JavaScript file:
function myFunc() {
alert(myValue);
}
MVC View file:
<script language="text/javascript">
myValue = #myValueFromModel;
</script>
I want to know how I can pass myValue directly as a parameter to the function ? I prefer to have explicit calling with param than relying on globals, however I'm not so keen on javascript.
How would I implement this with javascript parameters? Thanks!
Just have your function accept an argument and use that in the alert (or wherever).
external.js
function myFunc(value) {
alert(value);
}
someview.cshtml
<script>
myFunc(#myValueFromModel);
</script>
One thing to keep in mind though, is that if myValueFromModel is a string then it is going to come through as myFunc(hello) so you need to wrap that in quotes so it becomes myFunc('hello') like this
myFunc('#(myValueFromModel)');
Note the extra () used with razor. This helps the engine distinguish where the break between the razor code is so nothing odd happens. It can be useful when there are nested ( or " around.
edit
If this is going to be done multiple times, then some changes may need to take place in the JavaScript end of things. Mainly that the shown example doesn't properly depict the scenario. It will need to be modified. You may want to use a simple structure like this.
jsFiddle Demo
external.js
var myFunc= new function(){
var func = this,
myFunc = function(){
alert(func.value);
};
myFunc.set = function(value){
func.value = value;
}
return myFunc;
};
someview.cshtml
<script>
myFunc.set('#(myValueFromModel)');
myFunc();//can be called repeatedly now
</script>
I often find that JavaScript in the browser is typically conceptually tied to a specific element. If that's the case for you, you may want to associate the value with that element in your Razor code, and then use JavaScript to extract that value and use it in some way.
For example:
<div class="my-class" data-func-arg="#myValueFromModel"></div>
Static JavaScript:
$(function() {
$('.my-class').click(function() {
var arg = $(this).data('func-arg');
myFunc(arg);
});
});
Do you want to execute your function immediately? Or want to call the funcion with the parameter?
You could add a wrapper function with no parameter and inside call your function with the global var as a parameter. And when you need to call myFunc() you call it trough myFuncWrapper();
function myFuncWrapper(){
myFunc(myValue);
}
function myFunc(myParam){
//function code here;
}

How do I pass the name of a function as a parameter then reference that function later?

I want to pass the name of a function "testMath" as a string into a wrapper function called "runTest" as a parameter. Then inside 'runTest' I would call the function that was passed. The reason I'm doing this is because we have a set of generic data that will populate into variables regardless of the test, then a specific test can be called, based on whatever the user wants to test. I am trying to do this using javascript/jquery. In reality the function is much more complex including some ajax calls, but this scenario highlights the basic challenge.
//This is the wrapper that will trigger all the tests to be ran
function performMytests(){
runTest("testMath"); //This is the area that I'm not sure is possible
runTest("someOtherTestFunction");
runTest("someOtherTestFunctionA");
runTest("someOtherTestFunctionB");
}
//This is the reusable function that will load generic data and call the function
function runTest(myFunction){
var testQuery = "ABC";
var testResult = "EFG";
myFunction(testQuery, testResult); //This is the area that I'm not sure is possible
}
//each project will have unique tests that they can configure using the standardized data
function testMath(strTestA, strTestB){
//perform some test
}
Do you need the function names as string? If not, you can just pass the function like this:
runTheTest(yourFunction);
function runTheTest(f)
{
f();
}
Otherwise, you can call
window[f]();
This works, because everything in the 'global' scope is actually part of the window object.
Inside runTests, use something like this:
window[functionName]();
Make sure testMath in the global scope, though.
I preffer to use apply/call approach when passing params:
...
myFunction.call(this, testQuery, testResult);
...
More info here.

Jquery and javascript namepsace

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() });

How best to overwrite a Javascript object method

I'm using a framework that allows the include of JS files. At the top of my JS file I have something like:
<import resource="classpath:/templates/webscripts/org/mycompany/projects/library/utils.lib.js">
I want to override a fairly small method that is defined in the very large utils.lib.js file. Rather than make the change directly in utils.lib.js, a file that's part of the framework, I want to overwrite just one method. The utils.lib.js file has something that looks like:
var Evaluator =
{
/**
* Data evaluator
*/
getData: function Evaluator_getData(input)
{
var ans;
return ans;
},
...
}
I want to change just what the method getData does. Sorry for the basic question, but after importing the file which copies the JS contents into the top of my JS file, can I just do something like:
Evaluator.getData = function Mine_getData(input)
{
...
};
Yes, you can just reassign that method to your own function as you have proposed with:
Evaluator.getData = function Mine_getData(input)
{
...
};
This will successfully change what happens when the .getData(input) property is called.
Yes you can.
However Evaluator is not a proper 'class'. You can't write var x = new Evaluator();
So you are not overriding, but just changing the variable getData. That's why we say that in JavaScript, functions are first-class citizen, treated like any variable.

Unable to re-define a function in my javascript object

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.

Categories