Having issue with - what I supposed to be - basics scope fundamentals.
I am using Javascript with Require JS structure, here are where the issue occurs:
function GameManager() {
//This is the constructor of gamemanager.js file
this.body = $('body');
this.game = $('#game');
}
GameManager.prototype.createGame = function() {
//Code
//this line works
this.body.append(//Some HTML);
}
GameManager.prototype.showGame = function() {
//Code
//this line does not work wtf
this.game.removeClass("display-none");
//and this one does work.
$("#game").removeClass("display-none");
}
I am using this.body succefully so I want to use the same way for this.game but it doesnt work. I can manage to make it work by using directly $("#game") but it's making jquery running through the DOM everytime so not really optimized...
I certainly am missing some basics points here, can someone explain ?
Thanks
This is working for me. I can remove display-none class from div without a problem. It wont display however. You need to change css. this.body.css("display","block"); for example.
window.onload = function() {
function GameManager() {
//This is the constructor of gamemanager.js file
this.body = $('body');
this.game = $('#game');
}
GameManager.prototype.createGame = function() {
//Code
//this line works
this.body.append();
}
GameManager.prototype.showGame = function() {
//Code
this.body.css("display", "block");
//this line does not work wtf
this.game.removeClass("display-none");
//and this one does work.
//$("#game").removeClass("display-none");
}
var myGame = new GameManager();
myGame.showGame();
}
Related
I am trying to run some code endlessly. I want to use the setInterval() method for that. The problem I am having with my program is that it is not getting executed at all. I tried to find the error using the browser's console but it does not say any error. I checked all the methods that are called before setInterval() are exectued properly. Here is the basic code :-
"use strict";
var Main = {
//properties
initialize:
setInterval(this.gameLoop, 15);
},
gameLoop: function(){
}
//other methods
}
window.addEventListener("load", Main.initialize, false);
The problem is that this is referencing the window object instead of the main object. See this Fiddle
Solution 1
Change the setInterval to:
setInterval(Main.gameLoop, 15);
Solution 2
Change the load event to:
window.addEventListener("load", function() { Main.initialise.call(Main); }, false);
Object Way
function Main() {
// The constructor
}
Main.prototype.initialise = function() {
setInterval(function() {
this.gameLoop();
}, 15);
}
Main.prototype.gameLoop = function() {
// Do gameloop stuff
}
var main = new Main();
window.addEventListener("load", function() {
main.initialise();
}, false);
Please note, I'm using initialise instead of initialize because its how I spell it (Just in case you direct copy paste and wonder why its not working for some bits)
Hi I have written some javascript code to generate an iFrame and insert content inside. But I don't want to use setTimeout and I want to refactor the code. I tried to use document.ready() and window.onLoad() and they don't work.
This is my code:
onShow: function() {
//TODO: why 200 ms wait? why not wait for specific event
setTimeout(this.injectHtml.bind(this), 200);
},
injectHtml: function() {
var iframe = this.el;
if (iframe.contentWindow === null) { //Check for contentWindow for null.
$(iframe).html(this.params.html);
} else { //If contentWindow is present then open the document for writing.
iframe = iframe.contentWindow;
iframe.document.open('text/html');
iframe.document.write(this.params.html);
iframe.document.close();
$(this.el).on('load', function() {
var iframe = $(this).contents();
iframe.find("#langSelect").off("change");
iframe.find("#langSelect").on("change", function() { //If another language is selected from Dropdown.
abc.languages.setSelected($(this).val());
abc.elements.setLanguage();
Vent.trigger(Vent.Event.LANGUAGE_SELECTED, $(this).val());
});
});
}
}
I'm really confused here. Can anyone shed light?
I have tried this as well:
Case#1:
var _this=this;
$(document).ready(function(){
_this.injectHtml.bind(_this); //Does not work. Everything loads, I get empty page
});
Case#2:
window.onLoad = function(){
this.injectHtml.bind(this);
};
can anyone help?
I'm trying to implement a simple image slider on my website but it doesn't seem to want to work. Nothing happens at all. Nothing I can think of has worked thus far so I thought I'd ask here. This is my code.
window.onload = function(){
image = document.getElementById("slideShow");
index = 0;
setInterval(slide, 3000);
};
function slide(){
index++;
if(index >= 6) {index = 0;}
path = "images/Slideshow/image"+index+".jpeg";
image.setAttribute("src",path);
}
window.onload is pretty cheesy because nobody seems to agree on what onload actually means.
i would recommend you use
document.addEventListener("DOMContentLoaded", function(){
// code
});
Another thing u should be aware of is slow loading. If the scripts gets loaded after the ready event has been fired then your code will never trigger.
A solution is wrapping the ready function is a seperate module.
var eventReady;
(function(){
var funcArr = [];
eventReady = function(func){
funcArr.push(func);
}
document.addEventListener("DOMContentLoaded", function(){
for(var i=0;i<funcArr.length;i++){
try{
funcArr[i]();
}
catch(e){
throw(e);
}
finally{
continue;
}
};
eventReady = function(func){
func();
}
});
})();
and then use the module like:
eventReady(function(){
// code
})
I'm trying to up my js foo and start to use the module patter more but I'm struggling.
I have a main page with a jquery-ui element that pops up a dialog that loads an ajax requested page for data entry. The below code is contained within the popup ajax page.
After the pop up is loaded the Chrome console is able to see and execute ProtoSCRD.testing() just fine. If I try to run that in the jQuery.ready block on the page, I get:
Uncaught ReferenceError: ProtoSCRD is not defined
Yet i can execute toggleTypeVisable() in the ready block and life is good. Can anyone shed some light?
$(document).ready(function() {
setHoodStyleState();
$('#hood-style').change(function(){
hstyle = $('#hood-style').val();
if ( hstyle.indexOf('Custom') != -1) {
alert('Custom hood style requires an upload drawing for clarity.');
}
setHoodStyleState();
});
setCapsState();
$('#caps').change(function(){
setCapsState();
});
setCustomReturnVisibility();
$('#return').change(function(){ setCustomReturnVisibility(); });
toggleTypeVisable();
$('#rd_type').change(function(){
toggleTypeVisable();
});
ProtoSCRD.testing();
});
function toggleTypeVisable(){
if ( $('#rd_type').val() == 'Bracket' ) {
$('.endcap-ctl').hide();
$('.bracket-ctl').show();
}
if ( $('#rd_type').val() == 'Endcap' ) {
$('.bracket-ctl').hide();
$('.endcap-ctl').show();
}
if ( $('#rd_type').val() == 'Select One' ) {
$('.bracket-ctl').hide();
$('.endcap-ctl').hide();
}
}
ProtoSCRD = (function($, w, undefined) {
testing = function(){
alert('testing');
return '';
}
getDom = function(){
return $('#prd-order-lines-cnt');
}
return {
testing: testing,
getDom: getDom
};
}(jQuery, window));
calling the popup dialog like so - which is in fact in another ready in a diff file on the parent page:
// enable prototype button
$( "#proto-btn" ).click(function(e){
e.preventDefault();
showPrototype();
});
I don't know if it will solve your problems at all, but you are definitely missing several var statements you really should have:
var ProtoSCRD = (function($, w, undefined) {
var testing = function(){
alert('testing');
return '';
};
var getDom = function(){
return $('#prd-order-lines-cnt');
};
return {
testing: testing,
getDom: getDom
};
}(jQuery, window));
IMHO, it's best practice to use var for every variable you declare. (Function declarations do so implicitly.)
But I really don't know if this will help solve anything. But it should store everything in its proper scope.
Update
Here's one possible issue: if the document is already ready (say this is loading at the end of the body), then perhaps jQuery is running this synchronously. Have you tried moving the definition of ProtoSCRD above the document.ready block?
I'm trying to update contents of a chat located in div (div1) but only when the contents of div1 change (a message was submitted into db and picked up in div1).
I tried the solution from here but my get fails to compare the data.
This solution works perfectly but without content comparison:
window.onload = startInterval;
function startInterval()
{
setInterval("startTime();",2000);
}
function startTime()
{
jQuery('#div1').load('index.php #div1 > *');
}
This is the modification based on this, which fails:
window.onload = startInterval;
function startInterval()
{
setInterval("startTime();",2000);
}
function startTime()
{
var $main = $('#div1');
$.get('chat.php #div1', function (data)
{
if ($main.html() !== data) $main.html(data);
});
}
I tried various modifications of this code but to no avail...
I can't reload the entire page and I don't want to do this if not necessary since it makes the chat harder to read if you have to scroll trough the messages.
How can this be fixed?
UPDATE
Based on #T.J's suggestions I modified the code which now works perfectly:
window.onload = startInterval;
function startInterval()
{
setInterval(startTime,3000);
scrolDown();
}
function startTime()
{
var $main = $('#div1');
$.get('#div1', function (data)
{
elements = $(data);
thisHTML = elements.find("#div1").html();
if ($main.html() !== thisHTML) {
$main.html(thisHTML);
scrolDown();
}
});
}
The other problem was that get required library:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
which apparently was not required by the load which I used previously.
You want to use get, but you want the fragment feature of load, so you'll have to do that work yourself. Then remember what you got last time, and only update if it's not the same:
var lastHTML;
function startTime()
{
var $main = $('#div1');
$.get('chat.php', function (data) // <== Or index.php, the question has both
{
var elements, html;
// Turn the HTML into elements
elements = $(data);
// Get the HTML of *only* the contents of #div1
html = elements.find("#div1").html();
// If that has changed, use it
if (lastHTML !== thisHTML) {
lastHTML = thisHTML;
$main.html(thisHTML);
}
});
}
Note that that's a fairly basic implementation of the fragment feature (it doesn't, for instance, strip out scripts the way load does). You may want to look at how load does its fragment stuff and replicate that (the joy of open source).