Loading a script with jQuery in .NET MVC3 - javascript

I am currently loading a model with jQuery's .load. After it has been successfully loaded, I would like to execute some JavaScript which has dependencies on the loaded model.
buildFindOrderDialog: function () {
workflowDialogContent.load('../../csweb/Orders/FindOrderDialog/', function () {
$.getScript('~/Scripts/FindOrderDialogModel.js');
workflowDialog.dialog('open');
});
}
The load method executes the Order Controller's FindOrderDialog method which returns a ViewModel. After this has loaded, I want to run my FindOrderDialogModel javascript to affect the model client-side.
The above code does not properly load the javascript. I am wondering: does my controller have to provide a method for loading the javascript? The client has no concept of the relative path.
Of course, I could inline the script with the FindOrderDialog view, which would cause it to execute after load, but this seems like a bit of a hack.
UPDATE: My syntax was just a bit off. This works:
buildFindOrderDialog: function () {
workflowDialogContent.load('../../csweb/Orders/FindOrderDialog/', function () {
$.getScript('../Scripts/Orders/FindOrderDialogModel.js');
workflowDialog.dialog('open');
});
},

If I understand your question correctly, how about either
$.getScript('Scripts/FindOrderDialogModel.js');
Alternatively specify the full path:
$.getScript('/My/Full/Path/Scripts/FindOrderDialogModel.js');
Or finally, inject the relative path via ASP.NET:
$.getScript('<%= .NET CODE FOR RETRIEVING PATH USING THE ~ SIGN %>');

Related

Using Ruby Variables in JavaScript

I'm new to Ruby so I had a question in regards to using some variables throughout my codebase. I have a variable declared in my Ruby file as follows:
#pages = 350
Now, I know that in HAML, I can simply do:
-if #pages = 350, and in HAML with inline javascript, I can do something like:
:javascript
console.log("#{#pages}");
However, I am linking an external JavaScript file in my HAML document, and I was wondering if it would be possible to use my Ruby variables in my external JS document? I need some variables in order to build what I am trying to build. Thanks!
Update as per one of the answers:
In my HAML file, I have the following:
:javascript
printPages(3);
In my external JS file, I have:
$(function() {
window.printPages = function(pages) {
console.log(pages);
}
});
I you are loading static javascript files I really would not recommend trying to insert variables into that code.
Instead, think about how you would provide that to your javascript code.
You could send it to that code as an argument.
<script type="text/javascript" src="./my-external-script.js"></script>
:javascript
runMyExternalFunction(#{#pages})
Or you could add the variable as a data attribute on your page, and your javascript could look for that when it loads.
Haml:
%body data-pages=#pages
JS:
console.log(document.body.dataset.pages) // value of #pages
Update about your javascript:
Using jquery's on page ready event $() for declaring the function is a bad idea. That means that it waits for everything on the page to be compeletely loaded, and then declares the function your page needs.
What you should be doing is setting up all the function that will be needed right away, and then calling those functions when the page is loaded.
They way you have it, the page loads, printPages() is executed (which doesn't exist yet), and then after all that printPages is created and put into the global scope.
So remove the $() from your external script and add it to your HAML instead.
In fact, if your aren't doing anything super fancy with transpiling or bundling, then you can simply declare the function in your external JS file, and it will be available globally. This doesn't work with your code because they way you've declared the function, it would only be available to code within that $() callback.
// js file
function printPages(pages) {
console.log(pages);
}
HAML:
$(() => {
printPages({#pages})
})

Javascript Moodle

Hi I am fairly new to moodle. I have been trying to test if my Javascript runs but to no avail. Here is what I have:
In /videojs/amd/src I made a test.js file with a simple command
define(['jquery'], function() {
return {
init: function() {
// Put whatever you like here. $ is available
// to you as normal.
alert("It changed!!");
}
};
});
Then I grunt the file and everything succeed, and made minified. But when I go to the page it doesn't run. Now I read Moodle's Javascript Doc and I see it says
The idea here is that we will run the 'init' function from our (PHP) code to set things up. This is called from PHP like this...
Where do I call this PHP?
Somewhere in the page you are outputting, you need to add a call like this:
$PAGE->requires->js_call_amd('PLUGINTYPE_videojs/test', 'init);
It's not entirely clear from your example what sort of plugin you are creating, so whichever type you are creating (https://docs.moodle.org/dev/Plugin_types), you need to put it in the appropriate subdirectory for your site (e.g. /mod/videojs, /local/videojs, etc.), then add some sort of PHP script as the entry point for your plugin and call the js_call_amd function from there.

How to load multiple template files using requireJs?

I am using Require JS to load vendor files and templates in JS.
I want to call one function when all related templates are loaded in page.
Currently I need to nested call like below:
requirejs(['text!templates/stream/leaderboard_m.ejs'], function(Leaderboard_M)
{
requirejs(['text!templates/stream/leaderboard_tl.ejs'], function(Leaderboard_TL) {
loadLeadrboardData(Leaderboard_M, Leaderboard_TL);
});
});
I would like to do that in 1 statement:
How can I do that using require JS?
Take a look at this: http://requirejs.org/docs/api.html#defdep
This would be what you want:
define([
"./services/MyFirstService",
"./services/MySecondService",
"./services/MyThirdService",
],
function (
MyFirstService,
MySecondService,
MyThirdService
) {
// all files loaded and can be used now!
});
You can reduce it to this:
requirejs(['text!templates/stream/leaderboard_m.ejs',
'text!templates/stream/leaderboard_tl.ejs'],
loadLeadrboardData);
All items in the list passed to the require (aka. requirejs) call are loaded before the callback is loaded. And the callback is loaded with the result of each item in the list of dependencies, in the same order. So you can have requirejs call loadLeadrboardData directly.
(I'd expect the function to be properly spelled loadLeaderboardData, not loadLeadrboardData with a missing e, but this is tangential to the problem asked here.)

What is the standard workaround for dynamic js files

Is there a standard workaround for something like this in ASP.NET:
//myinclude.js
$(document).ready(function() {
for(recs=0; recs < {{server-side-value}}; recs++) {
// process records
}
});
Note this is a js file. I know about WinForms ability to insert dynamic quoted scripts into the page. But how about a page's js file that is dependent on server-side values? I know you can use something like:
//myview.cshtml
var instance = new MyObject(<%= ServerSideValue =%>);
and include it on the page to pass it to the js file, but I'm wondering about the architecture of keeping js separate from html code so that an html/css designer can work with the template free of javascript; keeping everything separate. I primarily use MVC now.
What are some of the patterns to deal with this? Is the only solution dynamically inserting js into the actual page or having partial views included separately into the page.? Or is there a way to sprinkle server-side values in separated js? In short, no dynamic js files?
I'm not trying to fix an exact project at this time, I have just been curious about this on past projects.
Thanks...
There are multiple ways to achieve this. One of the ways would be populating your data into a Javascript objects on the HTML page directly.
//myview.cshtml
<script>
var pageData = {
name : '#variable1',
value1: #value1
};
</script>
And, in the javascript file:
//pageUI.js
if (pageData) {
$('#page_tile').html(pageData.name);
}
I am sure you can optimize a whole lot (for example, having a single communication between the server side data and the client side code). At the end of the day, you want to make sure that your javascript code can be resusable.
for example one can do this:
A. have the main .js code read any context-specific parameters from the current window like this (page.js):
!function(window){
var configData = window.MyAppNameConfigData;
// rest app code here..
}(window);
B. the server side script can inject these context-specific data in the page's html like this:
<script>
window.MyAppNameConfigData = {
param1: //..
param2: //..
// etc..
};
</script>
Note if needed make sure that the page.js is enqueued/loaded after the data have been injected/inserted (using a script dependency chain for example)
If it's not "inline" (on the View/Page itself), you could do a Partial View/Page:
Trivial example: _PartialJs.cshtml
$(document).ready(function() {
var foo = "#DateTime.Now.Year";
});
Then in your view:
<script>
#Html.Partial("_PartialJs")
</script>
Renders:
<script>
$(document).ready(function() {
var foo = "2015";
});
</script>
Hth...

HTML5 drag event using a $(function() { ... } library

I have been playing around with HTML5 and Javascript for the first time and I am stuck. My question in short is how do I call a method (in html) inside a JS file which starts with
$(function() { ... }
Basically I used azure which gives you a code project to start but when it gave me the files there was a page.js which started with:
$(function() {
var client = new WindowsAzure.MobileServiceClient('[...]', '[...]'),
todoItemTable = client.getTable('todoitem');
...
The azure service has a very simple database which I need to use to create a Kanban boardesc webpage.
I made my task element draggable and added events to handle it but I am unable to create the event method in this JS file and if I have it in my HTML I am unable to call any of the methods in the .js
I have asked around work and no one seems to have seen the $(function() { ... } thing before and I can't find the info that I need anywhere.
Thanks
You do not call this method directly; the syntax you're looking at is JQuery's document.ready in other words this function gets called when your document is finished loading.
JQuery Link - Document.Ready
That is the jQuery shorthand for the $(document).ready(handler) function. Anything you put in the function will be executed when the document is finished loading.
jQuery ready function
That syntax is jQuery - specifically an an alias of the "DOMReady" function
( http://api.jquery.com/ready/ ) which is called after the DOM has finished loading.
Try looking at this question's suggested answer by Derick Bailey.
Why define an anonymous function and pass it jQuery as the argument?
He includes some sample code of how to write a code using a JavaScript Module pattern.
Good luck!
Anthony

Categories

Resources