Cocos2d-js sprite array touch event - javascript

var GameLayer = cc.Layer.extend({
ball:[],
number:[],
label:[],
numberofballs:8,
_order:0,
ctor:function () {
this._super();
this.init();
},
init:function(){
this._order=0;
cc.log(this._order);
this.setBall();
},
setCoordX:function(){
var coordX=Math.random()*1000%330+50;
cc.log(coordX);
return coordX;
},
setCoordY:function(){
var coordY = Math.random()*700%700+50;
cc.log(coordY);
return coordY;
},
onTouchBegan:function(touch, event){
var target = event.getCurrentTarget();
var PosInScreen = target.convertToNodeSpace(touch.getLocation());
var Size = target.getContentSize();
var rect = cc.rect(0, 0, Size.width, Size.height);
if(cc.rectContainsPoint(rect, PosInScreen)){
if(target.getTag()==this._order) {
target.removeFromParent();
this._order++;
}
}
return false;
},
setBall:function(){
for(var i=0;i<this.numberofballs;i++){
this.number.push(Math.round(Math.random()*100));
}
this.number.sort(function(left,right){
return left-right;
});
for(var i=0;i<this.numberofballs;i++){
var eventListener = cc.EventListener.create({
event: cc.EventListener.TOUCH_ONE_BY_ONE,
swallowTouches: true,
onTouchBegan: this.onTouchBegan});
this.ball[i]=cc.Sprite.create(res.ball_png);
this.ball[i].x=this.setCoordX();
this.ball[i].y=this.setCoordY();
this.ball[i].setTag(i);
this.addChild(this.ball[i]);
var label=new cc.LabelTTF(this.number[i],"Ariel",25);
label.x=50;
label.y=55;
this.ball[i].addChild(label);
cc.eventManager.addListener(eventListener, this.ball[i]);
}
}
});
var GameScene = cc.Scene.extend({
onEnter:function () {
this._super();
var layer = new GameLayer();
this.addChild(layer);
}
});
This is my whole code.
First, in setBall function, I added
cc.eventManager.addListener(eventListener, this.ball[i]);
I want to make touch event with this.ball array directly.
Second,in onTouchBegan function, this._order is null.
I don't know why.
How can I fix it?

this._order is undefined because in onTouchBegan function this is instance of cc.EventListener class.
If You want to make this to be instance of GameLayer, You can bind it:
var eventListener = cc.EventListener.create({
event: cc.EventListener.TOUCH_ONE_BY_ONE,
swallowTouches: true,
onTouchBegan: this.onTouchBegan.bind(this)});

Related

How can I get multiple variables from a function in javascript

I create a function buttonEffects() with four button effects (one effect for each). Therefore, I would like to know how can I bring these variables outside of this function and fetch them into another function? I don't know whether I am able to do that, or I will need to recreate my code.!?
I already return each of the var on the botton of the function buttonEffects() such as return (var1, var2, var3, var4); and declare them outside of it but with no success.
//jQuery
$(document).ready(function() {
let blueBtnAudio = new Audio('https://s3.amazonaws.com/freecodecamp/simonSound1.mp3');
let redBtnAudio = new Audio('https://s3.amazonaws.com/freecodecamp/simonSound2.mp3');
let yellowBtnAudio = new Audio('https://s3.amazonaws.com/freecodecamp/simonSound3.mp3');
let greenBtnAudio = new Audio('https://s3.amazonaws.com/freecodecamp/simonSound4.mp3');
// VARIABLES - DOM QUERIES
const btnBlue = "#btnBlue";
const btnGreen = "#btnGreen";
const btnRed = "#btnRed";
const btnYellow = "#btnYellow";
const startButton = "#startButton";
const randomColors = ['blueButtonEffect', 'greenButtonEffect', 'redButtonEffect', 'yellowButtonEffect'];
console.log('blueButtonEffect');
//button effects
function buttonEffects() {
//button blue effect
var blueButtonEffect = $(btnBlue).click(function() {
var originalColor = $(this).css('background-color');
blueBtnAudio.play();
$(this).css('background-color', '#00FFFF');
setTimeout(function() {
$(btnBlue).css('background-color', originalColor);
}, 100);
});
//button green effect
var greenButtonEffect = $(btnGreen).click(function() {
var originalColor = $(this).css('background-color');
greenBtnAudio.play();
$(this).css('background-color', '#7FFF00');
setTimeout(function() {
$(btnGreen).css('background-color', originalColor);
}, 100)
});
// button red effect
var redButtonEffect = $(btnRed).click(function() {
var originalColor = $(this).css('background-color');
redBtnAudio.play();
$(this).css('background-color', '#F08080');
setTimeout(function() {
$(btnRed).css('background-color', originalColor)
}, 100);
});
// button yellow effect
var yellowButtonEffect = $(btnYellow).click(function() {
var originalColor = $(this).css('background-color');
yellowBtnAudio.play();
$(this).css('background-color', '#F0E68C');
setTimeout(function() {
$(btnYellow).css('background-color', originalColor)
}, 100);
});
}
// start the game
function startGame() { // it has a bug if clicked twice!
$(startButton).on('click', buttonEffects);
};
startGame();
function changeColor() {
//some code here?
}
});
Now I am trying a new approach where I live each variable out of the function scope and declare only its var names within the function buttonEffects()
to return the same startGame() effect.To be honest, I am pretty lost!
new approach:
//button blue effect
var blueButtonEffect = $(btnBlue).click(function() {
var originalColor = $(this).css('background-color');
blueBtnAudio.play();
$(this).css('background-color', '#00FFFF');
setTimeout(function() {
$(btnBlue).css('background-color', originalColor);
}, 100);
});
//button green effect
var greenButtonEffect = $(btnGreen).click(function() {
var originalColor = $(this).css('background-color');
greenBtnAudio.play();
$(this).css('background-color', '#7FFF00');
setTimeout(function() {
$(btnGreen).css('background-color', originalColor);
}, 100)
});
// button red effect
var redButtonEffect = $(btnRed).click(function() {
var originalColor = $(this).css('background-color');
redBtnAudio.play();
$(this).css('background-color', '#F08080');
setTimeout(function() {
$(btnRed).css('background-color', originalColor)
}, 100);
});
// button yellow effect
var yellowButtonEffect = $(btnYellow).click(function() {
var originalColor = $(this).css('background-color');
yellowBtnAudio.play();
$(this).css('background-color', '#F0E68C');
setTimeout(function() {
$(btnYellow).css('background-color', originalColor)
}, 100);
});
return (blueButtonEffect, redButtonEffect, greenButtonEffect, yellowButtonEffect);
// start the game
function buttonEffects() {
var blueButtonEffect;//something else shold be here....
var redButtonEffect;
var greenButtonEffect;
var yellowButtonEffect;
function startGame() { // it has a bug if clicked twice!
$(startButton).on('click', buttonEffects);
}
startGame();
}
});
Return an object, like this:
function thing() {
return {
item1: 1,
other: {
item2: 2,
item3: 3
}
};
}
var things = thing();
var item1 = things.item1;
var item2 = things.other.item2;
var item3 = things.other.item3;
I find a way that may right if it is wrong please let me know.
function buttonEffects(){
var blueButtonEffect = code here;
var redButtonEffect = code here;
var greenButtonEffect = code here;
var yellowButtonEffect = code here;
return {
item1: blueButtonEffect,
item2: redButtonEffect,
item3: greenButtonEffect,
item4: yellowButtonEffect
};
}
var effects = buttonEffects();
var blueButtonEffect2 = effects.item1;
var redButtonEffect2 = effects.item2;
var greenButtonEffect2 = effects.item3;
var yellowButtonEffect2 = effects.item4;

Javascript / Jquery OOP not inheriting attributes

I have created a Constructor class / function that has 4 methods and a 5 attributes. The problem is when i create a new instance of the constructor it doesn't inherit the first attribute (this.el = element) which is 'affiliateSection' on the new instance called: animation1. Thanks in advance..
// main class
function AnimateImages(el, time, effect, setTime, h){
this.el = element; // this is not inheriting from 'animate1'
this.time = time;
this.effect = effect;
this.setTime = setTime;
this.h = height;
this.delayAnimate = function() {
this.element.delay(time)
.queue(function(next) {
$(this).addClass(effect);
next();
});
};
// function for multi animations
var multiAnimations = function() {
var i = 0;
this.element.each(function (key, value) {
i = i + setTime;
var tthis = this;
delayAnimate($(this), i, tthis.effect);
});
};
// load on window height
var onWindowAnimate = function () {
if ($(this).scrollTop() > this.height) {
// call multi animations function
var tthis = this;
multiAnimations(this.element, tthis.setTime, tthis.effect);
}
};
// hide function
var hideAnimatedEl = function (){
this.element.each(function(){
$(this).css("visibility", "hidden");
});
};
} // End of AnimateImages
/*============================================================*/
var affiliateSection = $("#aff-img > li > img");
// new instance of AnimateImages
var animation1 = new AnimateImages(affiliateSection, 200, 'subtlefadeIn',
300, 50);
$(window).scroll(function () {
setTimeout(function(){
animation1.onWindowAnimate();
}, 1000);
});
It looks like you have your member variable initializations backwards. Try this:
this.element = el; // this is not inheriting from 'animate1'
this.time = time;
this.effect = effect;
this.setTime = setTime;
this.height = h;
Your parameter name is wrong:
this.el = element;
element is not in the parameter list.
Since you are reffering to this.element inside your function, I am assuming that your first line should be
this.element = el;

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

Click eventlistener within 'class' referring to a function within that same class is not working

I can't figure out why this isn't working. The cThis.menuClick doesn't recieve the event, it does get called though.
// no event passed to cThis.menuClick
var Menu = new function() {
var cThis = this;
// .....
cThis.menuItems = cThis.element.querySelectorAll('#menu-items a.menu-item');
for(var i=0; i<cThis.menuItems.length; i++) {
cThis.menuItems[i].addEventListener('click', cThis.menuClick, false);
}
cThis.menuClick = function(event, returning) {
if (event) { event.preventDefault(); }
// not prevented
}
}
I solved the issue this way:
// event passed, working!
var Menu = new function() {
var cThis = this;
// .....
cThis.menuItems = cThis.element.querySelectorAll('#menu-items a.menu-item');
for(var i=0; i<cThis.menuItems.length; i++) {
cThis.menuItems[i].addEventListener('click', mC, false);
}
function mC(event) {
cThis.menuClick.call(this, event);
}
cThis.menuClick = function(event, returning) {
if (event) { event.preventDefault(); }
// prevented
}
}
Although this workaround is working, I whould like to know why the first code isn't?
Code is wrapped in a namespace:
var NS = new function() {
}
menuClick is not defined when the event is attached. Simply assign the function to the menuclick property prior to registering it with the event listener.
var Menu = new function() {
var cThis = this;
// .....
cThis.menuItems = cThis.element.querySelectorAll('#menu-items a.menu-item');
cThis.menuClick = function(event, returning) {
if (event) { event.preventDefault(); }
// not prevented
}
for(var i=0; i<cThis.menuItems.length; i++) {
cThis.menuItems[i].addEventListener('click', cThis.menuClick, false);
}
}

Removing eventhandlers not working: "this" context lost in Javascript?

I have a problem with removing the eventhandlers for a slider element
If I don't use proxy for the handler, the "this" will point to the dom element
How do I remove the handler?
Relevant code:
var slider = (function (slider) {
var Sliderhandle = function(handle){
EvtTarget.call(this);
this.events = {
start: ['touchstart', 'mousedown'],
move: ['touchmove', 'mousemove'],
end: ['touchend', 'touchcancel', 'mouseup']
};
this.options = {};
this.element = $$('div.ui-slider');
// set context for event handlers
this.start = this.start.bind(this);
this.move = this.move.bind(this);
this.end = this.end.bind(this);
this.proxy = function(func){
var that = this;
return(function(){
return func.apply(that,arguments);
});
}
Object.defineProperty(this, "__el",{
value:handle
});
};
Sliderhandle.prototype = Object.create(EvtTarget.prototype,{
init : {
value:function(config){
this.container = $$('div.ui-slider');
this.track = this.container.getElementsByClassName('ui-slider-track')[0];
this.value = (config && config.value) || 1;
this.min = (config && config.min) || 1;
this.max = (config && config.value) || 1000;
this.change = (config && config.change) || null; // callback
this.addEvents("start");
this.setValue(this.value);
},
enumerable:true
},
addEvents : {
value:function(name){
var list = this.events[name],
handler = this[name],
all;
handler = this.proxy(handler);
for (all in list){
this.container.addEventListener(list[all], handler, false);
}
},
enumerable:true
},
removeEvents:{
value:function(name){
var list = this.events[name],
handler = this[name],
all;
//handler = this.proxy(handler);
for (all in list){
this.container.removeEventListener(list[all], handler, false);
}
},
enumerable:true
},
The problem is because there's no event listener same with handler which passed to removeEventListener. this.proxy() generates new function for each call. It returns whole different function object even if you call it with same parameter, although the returned function will do semantically same job.
You should store proxy functions when add, then use that one when remove like this:
var Sliderhandle = function(handle){
// ....
this.proxyHandler = {};
}
// ....
addEvents : {
value: function(name){
var list = this.events[name],
handler = this[name],
all;
this.proxyHandler[name] = handler = this.proxy(handler);
for (all in list){
this.container.addEventListener(list[all], handler, false);
}
},
enumerable:true
},
removeEvents:{
value:function(name){
var list = this.events[name],
handler = this.proxyHandler[name],
all;
for (all in list){
this.container.removeEventListener(list[all], handler, false);
}
delete this.proxyHandler[name];
},
enumerable:true
},

Categories