Hello everyone,
I have just recently started learning the require.js , but I don't seem to understand as how does the whole mechanism work...and especialy how do I access the variables/objects created using this javascript library.
Let me explain it further in the example below..
webroot/page.jsp
<html>
<script data-main="js/page" src="js/lib/require.js"></script>
</html>
webroot/js/common.js
requirejs.config({
baseUrl: 'js/lib',
paths: {
app: '../app',
}
});
webroot/js/app/page.js
require(['./common'], function (common) {
require(['./app/page/init'], function(page)
{
page.load(1);
});
});
webroot/js/app/page/init.js
define(['./load'], function (load) {
var LoadPage = new load();
return LoadPage;
});
webroot/js/app/page/load.js
define(function () {
function loadPage() {
}
loadPage.prototype = {
load: function (page_id) {
console.log("Opening page "+page_id+" ");
}
};
return loadPage;
});
now when I run the page everything works perfectly, but now I'd like to execute the load method by clicking on a button.
<div onclick="page.load(2);"> </div>
but this does not work..So I'd like to know if there is any possibility to bind this action to any button or link...whatever..
(apologies for my bad english)
Thanks,
Alex
How about as below assuming you are using JQuery:
<div id="divPageLoad"></div>
<script language="javascript" type="text/javascript">
$("#divPageLoad").on("click", function() {
page.load(2);
});
</script>
Related
I have a template that I am using from template monster. In the files there is a javascript page that has all of the scripts needed to run the pages. I have added this to the bottom of the page where the scripts are rendered. It does not seem to be accessing the file. It is on the page and comes up when I am viewing it under the "Inspect object". When I put the code snippet directly in the razor page it works. Any ideas why it would not be pulling it from the javascript file? Thanks for your help.
EDIT
This resides in the _Layout page. Where the Menu is.
The below works when inserted in the razor page.
<script type="text/javascript">
$(document).ready(function () {
$(".sticky-menu").sticky({ topSpacing: 0 });
});
$(window).on('load', function () {
function fadeOut(el) {
el.style.opacity = 0.4;
var last;
var tick = function () {
el.style.opacity = +el.style.opacity - (new Date() - last) / 600;
last = +new Date();
if (+el.style.opacity > 0) {
(window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 100);
} else {
el.style.display = "none";
}
};
tick();
}
var pagePreloaderId = document.getElementById("page-preloader");
setTimeout(function () {
fadeOut(pagePreloaderId)
}, 1000);
});
</script>
This is what I have in the razor page that does not work
#Scripts.Render("~/Scripts/scripts.js")
The Top code resides in the "scripts.js" file.
There is a lot of code in this file and it seems like none of it is working. Meaning it is like it is not accessing the script. All the scripts that are loaded in the page are in the same order as the Regular HTML in the template. The template HTML file works.
UPDATE -
I got this to work by moving this out of the script page and onto the layout page. I am still not sure why or what was causing this snippet not to work in the script page. It seems like the only part that wasnt working.
In the script file it is written like this:
(function($) {
'use strict';
jQuery(document).on('ready', function() {
////// Other snippets //////
$(".sticky-menu").sticky({
topSpacing: 0
});
////// Other snippets //////
});
In the _Layout page it looks like this:
<script type="text/javascript">
$(document).ready(function () {
$(".sticky-menu").sticky({ topSpacing: 0 });
var hub = $.connection.notificationHub;
$.connection.hub.start()
.done(function () {
console.log("Hub Connected!");
})
.fail(function () {
console.log("Could not Connect!");
});
});
</script>
I still do not know why this does not work from the Script file...
UPDATE - 4-26-2019
I have found the problem. The Template was created with a earlier version of jQuery. I have found that the Script file loads and partially works when I remove
jQuery(document).on('ready', function () {
The entire file looks like this
(function($) {
'use strict';
jQuery(document).on('ready', function () {
---> All the jQuery Code
});
})(jQuery);
I changed the above line to be:
}(jQuery));
I saw some other implementations that had it this way.
However there is something not right with this using jQuery 3.3.1.. if anyone knows how to properly format this so it works that would help alot.
You change from
#Scripts.Render("~/Scripts/scripts.js")
to
<script src="~/Scripts/scripts.js"></script>
It will work
You can refer this link to understand different between Script.Render vs script tag
What is the difference between "#Script.Render" and "<script>"?
Update:
If you have a _Layout.cshtml view like this
<html>
<body>
#RenderBody()
#RenderSection("scripts", required: false)
</body>
</html>
then you can have an index.cshtml content view like this
#section scripts {
<script type="text/javascript" src="~/Scripts/scripts.js"></script>
}
My problem is that the jQuery load event is not working with my custom Javascript structure. I have tried many solutions to solve this problem but I failed.
var Init_Template = (function($) {
"use strict";
return {
init: function() {
this.plugins();
this.menus();
},
plugins: function() {
// Codes
},
menus: function() {
$(window).on("load", function(e) {
alert();
});
}
};
})(jQuery);
// Load when ready
jQuery(document).ready(function() {
function System_Init() {
Init_Template.init();
}
if (window.self === window.top) {
System_Init();
} else {
setTimeout(System_Init);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You will want that script with the jquery loading BEFORE you execute your javascript and jquery code so move the script tag above your code. I believe this will solve your issue for you.
I have a .NET web control that includes some JavaScript structured something like this:
<script type="text/javascript">
function doSomethingImportant() {
// Do something important here...
}
$(function () {
// A bunch of JavaScript/jQuery code here...
});
</script>
The doSomethingImportant() function is placed outside of my $(function() { ... }) block so it can be called from JavaScript on the page that hosts my web control.
But I would like this function to be able to access some code within the $(function() { ... }) block. Is this possible? Is there a better way to structure this?
If you add a code on window object in the jquery function you can call it from the outer function.
e.g.
<script type="text/javascript">
function doSomethingImportant() {
// Do something important here...
window.myfunc();
}
$(function () {
// A bunch of JavaScript/jQuery code here...
window.myfunc = function(){
}
});
</script>
I'm looking into the whole asynchronous script loading thing with Modernizr and yepnope.js and I'm wondering how I can adapt my application's structure to use asynchronous script loading.
Right now the structure resembles this:
...
<head>
<script src=jquery.js></script>
<script src=plugin1.js></script>
<script src=plugin2.js></script>
<script src=plugin3.js></script>
<script src=global.js></script>
</head>
<body>
This code is found in a header.php file that is required throughout the application. In the document body section (other PHP files), I may have some JavaScript files like this:
...
<script src=moduleA.js></script>
<script src=someScripts.js></script>
</html>
Here's a simplified example of what moduleA.js and someScripts.js could contain:
$(document).ready(function() {
$('.searchDate').myCoolPlugin({ /* some options */ });
});
And someScripts.js:
$(document).ready(function() {
$('#departureDate, #arrivalDate').myCoolPlugin({ /* some options */ });
});
If I'm using Modernizr, at the top of the page I would remove the other plugin scripts and in global.js I'd write:
Modernizr.load([
{
test: $.fn.myCoolPlugin,
nope: 'plugin1.js',
complete: function() {
$(document).ready(function() {
$('.filterDates').myCoolPlugin();
}
}
}
]);
How do I guarantee that myCoolPlugin has been loaded by the time moduleA.js and someScripts.js are executed? I realize that I can wrap the plugin initialization in those files with Modernizr.load(), but that seems like unnecessary duplication of code.
If I have understood your question correctly then you want to execute the body scripts after the necessary scripts have been loaded with Modernizr.
You could do something like this:
// Header script
var race_won = false;
var load_body_script = function() {
race_won = true;
};
Modernizr.load([
{
test: ..your condition..,
yep: ..test success..,
nope: ..test fail..,
complete: function() {
$(document).ready(function() {
$('.filterDates').myCoolPlugin();
load_body_script();
}
}
}
]);
// Body script
var body_script = function() {
// .. your code here ..
}
if (race_won) {
body_script();
}
else {
load_body_script = body_script;
}
I'm having a very strange and frustrating problem with RequireJS. When I call require for a module with a list of dependencies, all dependencies available in the callback reference a single module. This is probably easier to explained with code:
Including require.js script (with no data-main attribute)
<script type="text/javascript" src="/js/common/require.min.js" ></script>
Below that I include require my main.js (used in all pages of the site) which in the callback requires my page specific js.
<script type="text/javascript">
require(['/js/require/main.js'], function () {
require(['page/home_page']);
});
</script>
main.js
requirejs.config({
baseUrl: 'js/require'
});
requirejs(['base'],
function() {
var base = require('base');
base.init();
});
home_page.js
define(['home','searchbar'], function (home,searchbar){
console.log(home.init == searchbar.init); // This is always true !!!
home.init();
searchbar.init();
});
home.js
define(function(){
this.init = function(){
console.log('in home page');
}
return this;
});
searchbar.js
define(function(){
this.init = function(){
console.log('Now in the searchbar init')
}
return this;
});
The issue is in home_page.js both modules home and searchbar reference the same thing. What's strange is that now that I've simplified this example, it seems pretty random which one it chooses. Most times it's searchbar but every few refreshes it will be home.
Anyone have an ideas? Is it something terribly obvious?
EDIT: Simplified example and provided all module source.
You are assigning to this in both modules. This is not a good idea (excuse the pun). this will possibly be the window object in both cases. You could check by adding a
window.init === searchbar.init
test.
Rewrite the modules to return unique objects, like so:
define(function() {
return {
init: function() {
console.log('in home page');
}
};
});
and
define(function() {
return {
init: function() {
console.log('Now in the searchbar init');
}
};
});