javascript: How to reference a class from event - javascript

I have a class like this
var grid = function () {
this.cell = null;
this.loadImage = function () {
var image = new Image();
var object = this;
image.src = "blah";
$(image).load(function () {
object.cell = this;
});
}
this.showImage = function () {
alert(object.cell); // This should print [object Object] ... but it print null;
}
}
The showImage function is called after the image called loaded from loadImage function.
Does anyone know why object.cell is null... I have reference to this object in loadImage.

object is undefined in showImage.

This is what I think you should be doing:
var grid = function () {
this.cell = null;
this.loadImage = function () {
var image = new Image();
image.addEventListener("load", (function (obj) {
return function () {
obj.cell = this;
};
})(this));
image.src = "http://upload.wikimedia.org/wikipedia/commons/8/84/Example.svg";
}
this.showImage = function () {
alert(this.cell);
}
}

Related

Ping site with knockout.js

I want to ping a few sites using javascript, and found this pen and does what I want.
However, I don't understand when I add goo12121212gle.com to the list of sites as a test it comes up saying that the domain has responded but in the console log I see ERR_NAME_NOT_RESOLVED??
I am new to JS but I am not sure why the below script is both saying the site is there and not at the same time? Is something missing from the script?
function ping(ip, callback) {
if (!this.inUse) {
this.status = 'unchecked';
this.inUse = true;
this.callback = callback;
this.ip = ip;
var _that = this;
this.img = new Image();
this.img.onload = function () {
_that.inUse = false;
_that.callback('online');
};
this.img.onerror = function (e) {
if (_that.inUse) {
_that.inUse = false;
_that.callback('offline', e);
}
};
this.start = new Date().getTime();
this.img.src = "http://" + ip;
this.timer = setTimeout(function () {
if (_that.inUse) {
_that.inUse = false;
_that.callback('timeout');
}
}, 1500);
}
}
var PingModel = function (servers) {
var self = this;
var myServers = [];
ko.utils.arrayForEach(servers, function (location) {
myServers.push({
name: location,
status: ko.observable('unchecked')
});
});
self.servers = ko.observableArray(myServers);
ko.utils.arrayForEach(self.servers(), function (s) {
s.status('checking');
new ping(s.name, function (status, e) {
s.status(e ? "error" : status);
});
});
};
var komodel = new PingModel(['goo12121212gle.com','msn.com','104.46.36.174','23.97.201.12']);
ko.applyBindings(komodel);
https://codepen.io/lyellick0506/pen/NGJgry
Both the onerror- and onload-callback use "responded" as the message, so there is no way to differentiate between them:
this.img.onerror = function (e) {
if (_that.inUse) {
_that.inUse = false;
_that.callback('responded', e); // <--- change this to a different message
}
};
Alternatively you could just check if the e parameter has been set:
new ping(s.name, function (status, e) {
s.status(e ? "error" : status);
});

JavaScript image never finishes .onload

New user here.
I am making a hockey game using JavaScript, and I need all of the images to finish loading before the main function is called to avoid flickering.
There are four images used: skaterAmin.png, skaterBmin.png, goalieAmin.png, goalieBmin.png
I am getting stuck on 2 out of 4 .onload functions.
both loadSkaterImgA and loadSkaterImgB will change to true but both loadGoalieImgA and loadGoalieImgB remain false
also used console.log() to confirm they were actually stuck
I also double checked all image src's and they are correct
//load images before main draw function to avoid flickering
var loadSkaterImgA = false;
var loadGoalieImgA = false;
var loadSkaterImgB = false;
var loadGoalieImgB = false;
function preloadSkaterImgA() {
var skaterImgA = new Image();
skaterImgA.onload = function() {
completeSkaterImgA();
return;
}
skaterImgA.src = 'skaterAmin.png';
return skaterImgA;
}
function preloadGoalieImgA() {
var goalieImgA = new Image();
goalieImgA.onload = function() {
completeGoalieImgA();
return;
}
goalieImgA = 'goalieAmin.png';
return goalieImgA;
}
function preloadSkaterImgB(){
var skaterImgB = new Image();
skaterImgB.onload = function() {
completeSkaterImgB();
return;
}
skaterImgB.src = 'skaterBmin.png';
return skaterImgB;
}
function preloadGoalieImgB(){
var goalieImgB = new Image();
goalieImgB.onload = function() {
completeGoalieImgB();
return;
}
goalieImgB = 'goalieBmin.png';
return goalieImgB;
}
function completeSkaterImgA(){
loadSkaterImgA = true;
return loadSkaterImgA;
}
function completeGoalieImgA(){
loadGoalieImgA = true;
return loadGoalieImgA;
}
function completeSkaterImgB(){
loadSkaterImgB = true;
return loadSkaterImgB;
}
function completeGoalieImgB(){
loadGoalieImgB = true;
return loadGoalieImgB;
}
preloadSkaterImgA();
preloadGoalieImgA();
preloadSkaterImgB();
preloadGoalieImgB();
Thank you for reading
You just need to call your preload methods after the DOM (which waits until all images are loaded) has loaded:
window.onload = function () {
preloadSkaterImgA();
preloadGoalieImgA();
preloadSkaterImgB();
preloadGoalieImgB();
}

reaching the btn event outside the revealing patterned applied class

I have an revealing patterned applied class.How can I reach btnMenu event outside of the model
thanks.
MyModel= (function () {
var btnClickEvents = function () {
var btnMenu = $('.btnMenu').on('click', function () {
var date= $(this).attr("data-rezerve-date");
var statu= $(this).attr("data-rezerve-statu");
alert("click"+date+'---'+statu);
});
};
return {
initialize: initialize,
asignValues: asignValues,
getRezervationDateAndStatus: btnClickEvents.btnMenu//how can I reach this function outside of model
};
})();
update
I change my code as u show.and add one return function
MyModel = (function () {
var dt = "";
var statu = "";
var rvalue = {};
var btnClickEvents = function () {
$('.btnMenu').on('click', onBtnMenuClick);
};
function onBtnMenuClick(e) {
dt = $(this).attr("data-rezerve-date");
statu = $(this).attr("data-rezerve-statu");
rvalue.date = dt;
rvalue.statu = statu;
console.log(dt);
}
var getRezervationDateAndStatus = function () {
return rvalue;
};
return {
initialize: initialize,
asignValues: asignValues,
getRezervationDateAndStatus: getRezervationDateAndStatus
};
})();
and after include my module to my web page calling is like this,
MyModel.asignValues(rezervasyonTable,data);
MyModel.initialize();
var result = MyModel.getRezervationDateAndStatus();
console.log(result.date);
bu console log empty.
As you say it is a " revealing" pattern. You could see what you expose. To be able to use this function outside of the module change your code like this:
MyModel = (function () {
var btnClickEvents = function () {
$('.btnMenu').on('click', onBtnMenuClick);
};
function onBtnMenuClick(e) {
var date = $(this).attr("data-rezerve-date");
var statu = $(this).attr("data-rezerve-statu");
alert("click" + date + '---' + statu);
}
return {
initialize: initialize,
asignValues: asignValues,
getRezervationDateAndStatus: onBtnMenuClick
};
})();

jquery plugin, reference video element in DOM

I have started jQuery plugin where I want to retrieve the .duration and .currentTime on a HTML5 video, from within a bound .on('click', ) event.
I am struggling to capture this information within my plugin.registerClick function, here is my code:
(function ($) {
$.myPlugin = function (element, options) {
var defaults = {
videoOnPage: 0,
dataSource: 'data/jsonIntervals.txt',
registerClick: function () { }
}
var plugin = this;
plugin.settings = {}
var $element = $(element);
element = element;
plugin.init = function () {
plugin.settings = $.extend({}, defaults, options);
$element.on('click', plugin.registerClick);
getJsonIntervals();
}
plugin.registerClick = function () {
var duration = $('video').get(plugin.settings.videoOnPage).duration;
console.log('duration: ' + duration);
}
var startTimes = [];
var dataSet = false;
var getJsonIntervals = function () {
if (dataSet == false) {
//calls a $.getJSON method.
//populates startTimes
//updates dataSet = true;
};
}
plugin.init();
}
$.fn.myPlugin = function (options) {
return this.each(function () {
if (undefined == $(this).data('myPlugin')) {
var plugin = new $.myPlugin(this, options);
$(this).data('myPlugin', plugin);
}
})
};
})(jQuery);
$(function () {
$('#button1').myPlugin();
});
Here my sample jsFiddle Click Here
Seems to work for me:
plugin.registerClick = function () {
var video = $('video').get(0);
console.log('duration: ' + video.duration);
console.log('currenttime: ' + video.currentTime);
}
http://jsfiddle.net/p4w040uz/2/
You need to play the video first then click the button. The browser has to retrieve the meta data first before it can return it.
Additional reference material you can read up:
http://www.w3schools.com/tags/av_event_loadedmetadata.asp
http://www.w3.org/2010/05/video/mediaevents.html

JavaScript Anonymous Function and Input Params

I am trying to understand how to properly pass parameters to anonymous functions. It seems like my 'this' is not pointing to where I was hoping it would go. What am I doing wrong?
JSfiddle:
http://jsfiddle.net/Chiliyago/NvGs8/3/
function initUTCDate() {
var $date = new Date();
var $dateUTC = new Date($date.getUTCFullYear(), $date.getUTCMonth(), $date.getUTCDate(), $date.getUTCHours(), $date.getUTCMinutes(), $date.getUTCSeconds());
return $dateUTC;
}
$(function () {
var setUTCDateTime = function (timeType) {
var $input = $(this);
var $d = initUTCDate();
if (timeType == "GMT") {
$input.val($d.toGMTString());
} else {
$input.val("false");
}
};
$('input[data-ucw-currDateTime]').each(setUTCDateTime("GMT"));
});
Try using:
$(function () {
var setUTCDateTime = function (timeType) {
return function () {
var $input = $(this);
var $d = initUTCDate();
if (timeType == "GMT") {
$input.val($d.toGMTString());
} else {
$input.val("false");
}
};
};
$('input[data-ucw-currDateTime]').each(setUTCDateTime("GMT"));
});
DEMO: http://jsfiddle.net/NvGs8/4/

Categories