Dynamically changing javascript variable - javascript

I am making an AJAX calling using JQuery. I get back a JSON object containing HTML and Javascript. Within the javascript, there is a function Initialize(). This returned javascript from the AJAX call should replace the initial definition of Initialize() which was there before the AJAX call was made. So basically, I'm trying to dynamically change the code of the javascript function to code I get back from an AJAX call. Help? Thanks in advance.

I think you might be looking for something like this:
init = function() { alert("init"); };
hash = { "newInit" : function() { alert("newInit"); }};
init(); // alerts "init"
init = hash.newInit;
init(); // alerts "newInit"

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

fake jquery document.ready calls on pages without jquery

I wanted to use some data in another JS script which had a JQuery call $(document).ready(function() inside the block, but i did not want to use JQuery nor init the script, because i just wnat to use some of the predefined variables.
So simply using the script from external source ( as it might get changed ) but skipping the ready() call and just do some data manipulation afterwards.
I got it working with
<script>
var fakeJquery = function(fn) {
this.ready = function () {
return true;
}
};
var $ = function(fn) { return new fakeJquery();}
</script>
But i wonder if there is a better, easier way to do that?

Dynamic JavaScript files on Ajax Request creating conflict

I am using MVC3 with heavy usage of ajax to get Partial Views. If Partial view contains JavaScript then it is added as a new js file as shown in snapshot:
so If I have a js function:
function checkValue(){
//do work
}
on ajax call a new dynamic JS file will be added contained this function and it conflicts with old once.
myfile.js contained:
function checkValue(){
//do work
}
and 1.js (dynamic file) will contain it too
function checkValue(){
//do work
}
So when I call it due to presence in old file it call already present function which is outdated. How to solve this situation like new JavaScript replace old one.
Thanks
You can check whether something is defined and redefine it only if it is not:
var checkValue = checkValue || function () {
//do work
};
If you want your definitions to override each-other instead of defining the function with a name, define them on the global object each time:
window.checkValue = function () {
//do work
};

Can I Pass a JS Object or Reference to a JS Object to a Function in the HTML Markup?

Pretty noobish question, and I'm probably thinking about this wrong, but...
Is there a way to pass a javascript object (or a reference to it) to a javascript function within the HTML markup?
For example:
<script type="text/javascript">
var myObject = new Object();
$('body').append('<div onclick=testThis(' + myObject + ')></div>');
function testThis(object)
{
console.log(object);
}
</script>
The markup ends up looking something like this when I inspect it:
<div onclick="testThis([object Object])">
Additional context:
The real use case is a search page in which I am querying SOLR via AJAX and get a result back as JS objects. When the user clicks on the HTML markup representing one of these search results, I want to be able to pass the object(or a reference to it) to a separate JS function for processing.
Am I thinking about this the wrong way?
No, you can't embed a reference to an object into markup.
Instead you probably would like to setup your click event listening in Javascript/jQuery:
var object = new Object();
$('<div/>').appendTo('body').click(function() {
testThis(object);
});
function testThis(value) {
console.log(value);
}

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

Categories