Find out Button position in array of objects - arrays

I've created a Button symbol and export it Export for ActionScript with class name "theButton".
There is an object and i would like to create that Button in myObj constructor as below :
public class myObj extends Sprite {
private var myBtn:theButton = new theButton();
public function myObj() {
x = Math.floor(Math.random() * 300) + 50;
y = Math.floor(Math.random() * 300) + 50;
addChild(myBtn);
}
public function getXPos():uint {
return x;
}
}
I'm trying to create an array of myObj class and getXPos() when i do clicking on each button like so :
var myArray:Array = new Array();
myArray[0] = new myObj();
myArray[0].addEventListener(MouseEvent.CLICK, Clicked);
addChild(myArray[0]);
function Clicked(evt:MouseEvent):void {
var xPos1:uint = myObj(evt.target).getXPos();
trace("Position is in : " + xPos1);
}
When clicking on the buttons appears on the screen, following error has comes up:
Type Coercion failed: cannot convert theButton#2c9dcf99 to myObj.
Please tell me what am i doing wrong ?

evt.target will contain a reference to the clicked display object, which actually is myBtn inside the myObj class (it's the only visible graphics you can click on).
There are two ways to solve this.
Set this.mouseChildren = false inside the myObj() constructor.
This way a click on a child display object in myObj will be
"counted" as a click on myObj, and evt.target will be a reference to
an instance of myObj.
Instead of evt.target use evt.currentTarget. It's the instance
you attached the event listener to, not the instance you clicked on
(That is actually what you want in most cases).

Related

mousemove event, access to this context

Fisrt of all I'm using D3js inside a React component so I use some variable of my class to save datas e.g.: this.graphicalId = 'test';
I have two items in my d3 element, svgViewport which is a g element and streams which are path elements. I have .on('mousemove' event handle for each.
In the streams event I would like save the name of the current stream using d3.select(this) (note I'm in a function() and not an arrow function so this is local) in a global variable in order to use it in the svgViewport event.
My problem is that like I'm in a function() this is local and not link to my class instance so I can't save the value in a member variable this.currentStreamName.
A bit of code :
svgViewport.on('mousemove', function (d, i) {
if (mouseIsOverStream) {
let mousex = d3.mouse(this);
mousex = mousex[0];
// here I want this of the class instance context
this.nearestTickPosition, this.currentStreamName = findNearestTickPosition(mousex);
}
});
Do you have some advices to deal with it ?
Thanks.
You can use arrow functions to get access to the instance's this context and still acquire the current DOM element. For the DOM element you resort to the little-known and often overlooked third parameter of the event listener. As the docs have it (emphasis mine):
the specified listener will be evaluated for the element, being passed the current datum (d), the current index (i), and the current group (nodes)
Since the current index i is the pointer into the current group nodes you can refer to the current DOM element as nodes[i].
Your code thus becomes:
svgViewport.on('mousemove', (d, i, nodes) => {
if (mouseIsOverStream) {
let mousex = d3.mouse(nodes[i]); // get the current element as nodes[i]
mousex = mousex[0];
// this now refers to your instance
this.nearestTickPosition, this.currentStreamName = findNearestTickPosition(mousex);
}
});
Store the class context in a variable out of the event binding. Then, make an IIFE and bind it's context to the stored one.
componentDidMount() {
const ctx = this;
svgViewport.on('mousemove', function (d, i) {
if (mouseIsOverStream) {
let mousex = d3.mouse(this);
mousex = mousex[0];
!function () {
// here I want this of the class instance context
this.nearestTickPosition, this.currentStreamName = findNearestTickPosition(mousex);
}.bind(ctx)();
}
});
}
Also, this should work too:
componentDidMount() {
svgViewport = ...;
svgViewport.on('mousemove', (d, i) => {
if (mouseIsOverStream) {
let mousex = d3.mouse(svgViewport); // here
mousex = mousex[0];
this.nearestTickPosition, this.currentStreamName = findNearestTickPosition(mousex);
}
});
}

Super keyword doesn't work with variables when trying to extend p5.js library

I want to extend the p5.js library in order to have error text on various locations on the screen. I will be using it in different places throughout my app and I believe it's better to do this than duplicating the code.
For now, almost everything is working fine, except some properties. For example, if I access super.height I'll get 0, while if I access this.height I'll get the actual window height. But, when accessing this.height I get an error saying that height isn't defined in CustomP5, which is right, but at the same time confusing.
import * as p5 from 'p5';
export class CustomP5 extends p5 {
... // private fields not related to this issue
constructor(sketch, htmlElement) {
super(sketch, htmlElement);
// Set tooltip error variables
this.resetTooltipError();
}
setSetup(setupFunction) {
super.setup = () => {
setupFunction();
this.setupAdditional();
}
}
setDraw(drawFunction) {
super.draw = () => {
drawFunction();
this.drawAdditional();
};
}
showTooltipError() {
...
}
Is there a reason why super.height, super.mouseX, and super.mouseY don't work, while super.draw or super.mousePressed are working correctly?
PS: I'm quite new to js and ts, so be patient if I'm wrong, please.
I'm not an expert, but it sounds like super only works with functions, not variables.
You say it works with super.draw and super.mousePressed. These are both functions. You say it does not work with super.height, super.mouseX, or super.mouseY. All of these are variables.
This matches the MDN docs for super:
The super keyword is used to access and call functions on an object's parent.
class Rectangle {
constructor(height, width) {
this.name = 'Rectangle';
this.height = height;
this.width = width;
}
sayName() {
console.log('Hi, I am a ', this.name + '.');
}
get area() {
return this.height * this.width;
}
set area(value) {
this.height = this.width = Math.sqrt(value);
}
}
class Square extends Rectangle {
constructor(length) {
this.height; // ReferenceError, super needs to be called first!
// Here, it calls the parent class' constructor with lengths
// provided for the Rectangle's width and height
super(length, length);
// Note: In derived classes, super() must be called before you
// can use 'this'. Leaving this out will cause a reference error.
this.name = 'Square';
}
}
So it sounds like this is working as intended. You might want to take some time to read up on how inheritance and the super keyword work in JavaScript.

I can call method on current form(first form) before another form(second form) called from side menu

I'm using addSideMenu(this) in every form to add the side menu.Menu items are defined in ENUM MenuOptions. In my case, I want to do some processing on controls before another form gets called from every form. If this is happening through any of the buttons or controls present on the form, then I can do processing and then calling the next form.
I'm having difficulty in doing the same when form is called from Side Menu. I have to do processing based on the elements present in the form and every form has different elements. This cannot be generic method. I don't understand how can I do the same thing, if another form gets called from Side Menu. Please advise.
Example: I'm on form "Start" (First Form) it has buttons "A" and button "B". I call form "Settings" from side Menu --> then I want to access Buttons A and B of form "Start"(first form) before control moves to Settings form.
Code for Side Menu:
public static void addSideMenu(Form f) {
Toolbar tb = f.getToolbar();
Button logout = new Button("Sign Out");
logout.setUIID("SignoutButton");
for (MenuOptions m : Server.instance.getMenuSortOrder()) {
m.addToSidemenu(tb);
}
tb.addComponentToSideMenu(logout);
}
Code for Side Menu options:
public enum MenuOptions {
SCHEDULE("Sch", "Schedule", FontImage.MATERIAL_PERM_CONTACT_CALENDAR,
e -> new AppointmentsForm(false, true, true,
Server.AppointmentFolders.APPOINTMENTS).show()),
ACTIVITY("Start", "Activity", FontImage.MATERIAL_ASSIGNMENT,
e -> new ActivityForm("").show()),
SETTINGS("Settings", "Settings", FontImage.MATERIAL_SETTINGS,
e -> new SettingsForm().show());
}
MenuOptions(String name, String title, char icon,
ActionListener<ActionEvent> al) {
this.name = name;
this.title = title;
this.icon = icon;
this.al = al;
}
public Component createMenuButton() {
Button b = new Button(title);
if (Display.getInstance().isTablet()) {
FontImage.setMaterialIcon(b, icon, 20);
} else {
FontImage.setMaterialIcon(b, icon, 10);
}
Font mediumBoldProportionalFont =
Font.createSystemFont(Font.FACE_PROPORTIONAL, Font.STYLE_BOLD,
Font.SIZE_MEDIUM);
b.getUnselectedStyle().setFont(mediumBoldProportionalFont);
b.getAllStyles().setBorder(Border.createEtchedRaised());
b.addActionListener(al);
return b;
}
I'm guessing the ENUM accepts an action listener. I suggest replacing that with a LazyValue<Form> which will create the form lazily for you. Then you can implement an action listener as:
Form f = lazy.getValue();
doSomethingOnForm(f);
f.show();

what is purpose of bind in reactJS [duplicate]

What is the use of bind() in JavaScript?
Bind creates a new function that will force the this inside the function to be the parameter passed to bind().
Here's an example that shows how to use bind to pass a member method around that has the correct this:
var myButton = {
content: 'OK',
click() {
console.log(this.content + ' clicked');
}
};
myButton.click();
var looseClick = myButton.click;
looseClick(); // not bound, 'this' is not myButton - it is the globalThis
var boundClick = myButton.click.bind(myButton);
boundClick(); // bound, 'this' is myButton
Which prints out:
OK clicked
undefined clicked
OK clicked
You can also add extra parameters after the 1st (this) parameter and bind will pass in those values to the original function. Any additional parameters you later pass to the bound function will be passed in after the bound parameters:
// Example showing binding some parameters
var sum = function(a, b) {
return a + b;
};
var add5 = sum.bind(null, 5);
console.log(add5(10));
Which prints out:
15
Check out JavaScript Function bind for more info and interactive examples.
Update: ECMAScript 2015 adds support for => functions. => functions are more compact and do not change the this pointer from their defining scope, so you may not need to use bind() as often. For example, if you wanted a function on Button from the first example to hook up the click callback to a DOM event, the following are all valid ways of doing that:
var myButton = {
... // As above
hookEvent(element) {
// Use bind() to ensure 'this' is the 'this' inside click()
element.addEventListener('click', this.click.bind(this));
}
};
Or:
var myButton = {
... // As above
hookEvent(element) {
// Use a new variable for 'this' since 'this' inside the function
// will not be the 'this' inside hookEvent()
var me = this;
element.addEventListener('click', function() { me.click() });
}
};
Or:
var myButton = {
... // As above
hookEvent(element) {
// => functions do not change 'this', so you can use it directly
element.addEventListener('click', () => this.click());
}
};
The simplest use of bind() is to make a function that, no matter
how it is called, is called with a particular this value.
x = 9;
var module = {
x: 81,
getX: function () {
return this.x;
}
};
module.getX(); // 81
var getX = module.getX;
getX(); // 9, because in this case, "this" refers to the global object
// create a new function with 'this' bound to module
var boundGetX = getX.bind(module);
boundGetX(); // 81
Please refer to this link on MDN Web Docs for more information:
Function.prototype.bind()
bind allows-
set the value of "this" to an specific object. This becomes very helpful as sometimes this is not what is intended.
reuse methods
curry a function
For example, you have a function to deduct monthly club fees
function getMonthlyFee(fee){
var remaining = this.total - fee;
this.total = remaining;
return this.name +' remaining balance:'+remaining;
}
Now you want to reuse this function for a different club member. Note that the monthly fee will vary from member to member.
Let's imagine Rachel has a balance of 500, and a monthly membership fee of 90.
var rachel = {name:'Rachel Green', total:500};
Now, create a function that can be used again and again to deduct the fee from her account every month
//bind
var getRachelFee = getMonthlyFee.bind(rachel, 90);
//deduct
getRachelFee();//Rachel Green remaining balance:410
getRachelFee();//Rachel Green remaining balance:320
Now, the same getMonthlyFee function could be used for another member with a different membership fee. For Example, Ross Geller has a 250 balance and a monthly fee of 25
var ross = {name:'Ross Geller', total:250};
//bind
var getRossFee = getMonthlyFee.bind(ross, 25);
//deduct
getRossFee(); //Ross Geller remaining balance:225
getRossFee(); //Ross Geller remaining balance:200
From the MDN docs on Function.prototype.bind() :
The bind() method creates a new function that, when called, has its
this keyword set to the provided value, with a given sequence of
arguments preceding any provided when the new function is called.
So, what does that mean?!
Well, let's take a function that looks like this :
var logProp = function(prop) {
console.log(this[prop]);
};
Now, let's take an object that looks like this :
var Obj = {
x : 5,
y : 10
};
We can bind our function to our object like this :
Obj.log = logProp.bind(Obj);
Now, we can run Obj.log anywhere in our code :
Obj.log('x'); // Output : 5
Obj.log('y'); // Output : 10
This works, because we bound the value of this to our object Obj.
Where it really gets interesting, is when you not only bind a value for this, but also for its argument prop :
Obj.logX = logProp.bind(Obj, 'x');
Obj.logY = logProp.bind(Obj, 'y');
We can now do this :
Obj.logX(); // Output : 5
Obj.logY(); // Output : 10
Unlike with Obj.log, we do not have to pass x or y, because we passed those values when we did our binding.
Variables has local and global scopes. Let's suppose that we have two variables with the same name. One is globally defined and the other is defined inside a function closure and we want to get the variable value which is inside the function closure. In that case we use this bind() method. Please see the simple example below:
var x = 9; // this refers to global "window" object here in the browser
var person = {
x: 81,
getX: function() {
return this.x;
}
};
var y = person.getX; // It will return 9, because it will call global value of x(var x=9).
var x2 = y.bind(person); // It will return 81, because it will call local value of x, which is defined in the object called person(x=81).
document.getElementById("demo1").innerHTML = y();
document.getElementById("demo2").innerHTML = x2();
<p id="demo1">0</p>
<p id="demo2">0</p>
Summary:
The bind() method takes an object as an first argument and creates a new function. When the function is invoked the value of this in the function body will be the object which was passed in as an argument in the bind() function.
How does this work in JS anyway
The value of this in javascript is dependent always depends on what Object the function is called. The value of this always refers to the object left of the dot from where is the function is called. In case of the global scope this is window (or global in nodeJS). Only call, apply and bind can alter the this binding differently. Here is an example to show how the this keyword works:
let obj = {
prop1: 1,
func: function () { console.log(this); }
}
obj.func(); // obj left of the dot so this refers to obj
const customFunc = obj.func; // we store the function in the customFunc obj
customFunc(); // now the object left of the dot is window,
// customFunc() is shorthand for window.customFunc()
// Therefore window will be logged
How is bind used?
Bind can help in overcoming difficulties with the this keyword by having a fixed object where this will refer to. For example:
var name = 'globalName';
const obj = {
name: 'myName',
sayName: function () { console.log(this.name);}
}
const say = obj.sayName; // we are merely storing the function the value of this isn't magically transferred
say(); // now because this function is executed in global scope this will refer to the global var
const boundSay = obj.sayName.bind(obj); // now the value of this is bound to the obj object
boundSay(); // Now this will refer to the name in the obj object: 'myName'
Once the function is bound to a particular this value we can pass it around and even put it on properties on other objects. The value of this will remain the same.
The bind() method creates a new function instance whose this value is bound to the value that was passed into bind().
For example:
window.color = "red";
var o = { color: "blue" };
function sayColor(){
alert(this.color);
}
var objectSayColor = sayColor.bind(o);
objectSayColor(); //blue
Here, a new function called objectSayColor() is created from sayColor() by calling bind() and passing in the object o. The objectSayColor() function has a this value equivalent to o, so calling the function, even as a global call, results in the string “blue” being displayed.
Reference : Nicholas C. Zakas - PROFESSIONAL JAVASCRIPT® FOR WEB DEVELOPERS
I will explain bind theoretically as well as practically
bind in javascript is a method -- Function.prototype.bind . bind is a method. It is called on function prototype. This method creates a function whose body is similar to the function on which it is called but the 'this' refers to the first parameter passed to the bind method. Its syntax is
var bindedFunc = Func.bind(thisObj,optionsArg1,optionalArg2,optionalArg3,...);
Example:--
var checkRange = function(value){
if(typeof value !== "number"){
return false;
}
else {
return value >= this.minimum && value <= this.maximum;
}
}
var range = {minimum:10,maximum:20};
var boundedFunc = checkRange.bind(range); //bounded Function. this refers to range
var result = boundedFunc(15); //passing value
console.log(result) // will give true;
Creating a new Function by Binding Arguments to Values
The bind method creates a new function from another function with one or more arguments bound to specific values, including the implicit this argument.
Partial Application
This is an example of partial application. Normally we supply a function with all of its arguments which yields a value. This is known as function application. We are applying the function to its arguments.
A Higher Order Function (HOF)
Partial application is an example of a higher order function (HOF) because it yields a new function with a fewer number of argument.
Binding Multiple Arguments
You can use bind to transform functions with multiple arguments into new functions.
function multiply(x, y) {
return x * y;
}
let multiplyBy10 = multiply.bind(null, 10);
console.log(multiplyBy10(5));
Converting from Instance Method to Static Function
In the most common use case, when called with one argument the bind method will create a new function that has the this value bound to a specific value. In effect this transforms an instance method to a static method.
function Multiplier(factor) {
this.factor = factor;
}
Multiplier.prototype.multiply = function(x) {
return this.factor * x;
}
function ApplyFunction(func, value) {
return func(value);
}
var mul = new Multiplier(5);
// Produces garbage (NaN) because multiplying "undefined" by 10
console.log(ApplyFunction(mul.multiply, 10));
// Produces expected result: 50
console.log(ApplyFunction(mul.multiply.bind(mul), 10));
Implementing a Stateful CallBack
The following example shows how using binding of this can enable an object method to act as a callback that can easily update the state of an object.
function ButtonPressedLogger()
{
this.count = 0;
this.onPressed = function() {
this.count++;
console.log("pressed a button " + this.count + " times");
}
for (let d of document.getElementsByTagName("button"))
d.onclick = this.onPressed.bind(this);
}
new ButtonPressedLogger();
<button>press me</button>
<button>no press me</button>
As mentioned, Function.bind() lets you specify the context that the function will execute in (that is, it lets you pass in what object the this keyword will resolve to in the body of the function.
A couple of analogous toolkit API methods that perform a similar service:
jQuery.proxy()
Dojo.hitch()
Bind Method
A bind implementation might look something like so:
Function.prototype.bind = function () {
const self = this;
const args = [...arguments];
const context = args.shift();
return function () {
return self.apply(context, args.concat([...arguments]));
};
};
The bind function can take any number of arguments and return a new function.
The new function will call the original function using the JS Function.prototype.apply method.The apply method will use the first argument passed to the target function as its context (this), and the second array argument of the apply method will be a combination of the rest of the arguments from the target function, concat with the arguments used to call the return function (in that order).
An example can look something like so:
function Fruit(emoji) {
this.emoji = emoji;
}
Fruit.prototype.show = function () {
console.log(this.emoji);
};
const apple = new Fruit('🍎');
const orange = new Fruit('🍊');
apple.show(); // 🍎
orange.show(); // 🍊
const fruit1 = apple.show;
const fruit2 = apple.show.bind();
const fruit3 = apple.show.bind(apple);
const fruit4 = apple.show.bind(orange);
fruit1(); // undefined
fruit2(); // undefined
fruit3(); // 🍎
fruit4(); // 🍊
/**
* Bind is a method inherited from Function.prototype same like call and apply
* It basically helps to bind a function to an object's context during initialisation
*
* */
window.myname = "Jineesh";
var foo = function(){
return this.myname;
};
//IE < 8 has issues with this, supported in ecmascript 5
var obj = {
myname : "John",
fn:foo.bind(window)// binds to window object
};
console.log( obj.fn() ); // Returns Jineesh
Consider the Simple Program listed below,
//we create object user
let User = { name: 'Justin' };
//a Hello Function is created to Alert the object User
function Hello() {
alert(this.name);
}
//since there the value of this is lost we need to bind user to use this keyword
let user = Hello.bind(User);
user();
//we create an instance to refer the this keyword (this.name);
Simple Explanation:
bind() create a new function, a new reference at a function it returns to you.
In parameter after this keyword, you pass in the parameter you want to preconfigure. Actually it does not execute immediately, just prepares for execution.
You can preconfigure as many parameters as you want.
Simple Example to understand bind:
function calculate(operation) {
if (operation === 'ADD') {
alert('The Operation is Addition');
} else if (operation === 'SUBTRACT') {
alert('The Operation is Subtraction');
}
}
addBtn.addEventListener('click', calculate.bind(this, 'ADD'));
subtractBtn.addEventListener('click', calculate.bind(this, 'SUBTRACT'));
The bind function creates a new function with the same function body as the function it is calling .It is called with the this argument .why we use bind fun. : when every time a new instance is created and we have to use first initial instance then we use bind fun.We can't override the bind fun.simply it stores the initial object of the class.
setInterval(this.animate_to.bind(this), 1000/this.difference);
function.prototype.bind() accepts an Object.
It binds the calling function to the passed Object and the returns
the same.
When an object is bound to a function, it means you will be able to
access the values of that object from within the function using
'this' keyword.
It can also be said as,
function.prototype.bind() is used to provide/change the context of a
function.
let powerOfNumber = function(number) {
let product = 1;
for(let i=1; i<= this.power; i++) {
product*=number;
}
return product;
}
let powerOfTwo = powerOfNumber.bind({power:2});
alert(powerOfTwo(2));
let powerOfThree = powerOfNumber.bind({power:3});
alert(powerOfThree(2));
let powerOfFour = powerOfNumber.bind({power:4});
alert(powerOfFour(2));
Let us try to understand this.
let powerOfNumber = function(number) {
let product = 1;
for (let i = 1; i <= this.power; i++) {
product *= number;
}
return product;
}
Here, in this function, this corresponds to the object bound to the function powerOfNumber. Currently we don't have any function that is bound to this function.
Let us create a function powerOfTwo which will find the second power of a number using the above function.
let powerOfTwo = powerOfNumber.bind({power:2});
alert(powerOfTwo(2));
Here the object {power : 2} is passed to powerOfNumber function using bind.
The bind function binds this object to the powerOfNumber() and returns the below function to powerOfTwo. Now, powerOfTwo looks like,
let powerOfNumber = function(number) {
let product = 1;
for(let i=1; i<=2; i++) {
product*=number;
}
return product;
}
Hence, powerOfTwo will find the second power.
Feel free to check this out.
bind() function in Javascript
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
An example for the first part
grabbed from react package useSt8
import { useState } from "react"
function st8() {
switch(arguments.length) {
case 0: return this[0]
case 1: return void this[1](arguments[0])
default: throw new Error("Expected 0 or 1 arguments")
}
}
function useSt8(initial) {
// this in st8 will be something like [state, setSatate]
return st8.bind(useState(initial))
}
// usage
function Counter() {
const count = useSt8(0);
return (
<>
Count: {count()}
<button onClick={() => count(0)}>Reset</button>
<button onClick={() => count(prevCount => prevCount + 1)}>inc</button>
</>
);
}
An example for the second part
const add = (a, b) => a+b
someThis = this
// new function with this value equal to someThis
add5 = add.bind(someThis, 5)
add5(10) // 15
// we don't use this in add decelartion so this will work too.
add10 = add.bind(null, 10)
add10(5) // 15
Here's the simplest possible explanation:
Say you have a function
function _loop(n) { console.log("so: " + n) }
obviously you can call it like _loop(69) as usual.
Rewrite like this:
var _loop = function() { console.log("so: " + this.n) }
Notice there are now
no arguments as such
you use "this. " to get to the named arguments
You can now call the function like this:
_loop.bind( {"n": 420} )
That's it.
Most typical use case:
A really typical use is when you need to add an argument to a callback.
Callbacks can't have arguments.
So just "rewrite" the callback as above.
Simple example
function lol(second, third) {
console.log(this.first, second, third);
}
lol(); // undefined, undefined, undefined
lol('1'); // undefined, "1", undefined
lol('1', '2'); // undefined, "1", "2"
lol.call({first: '1'}); // "1", undefined, undefined
lol.call({first: '1'}, '2'); // "1", "2", undefined
lol.call({first: '1'}, '2', '3'); // "1", "2", "3"
lol.apply({first: '1'}); // "1", undefined, undefined
lol.apply({first: '1'}, ['2', '3']); // "1", "2", "3"
const newLol = lol.bind({first: '1'});
newLol(); // "1", undefined, undefined
newLol('2'); // "1", "2", undefined
newLol('2', '3'); // "1", "2", "3"
const newOmg = lol.bind({first: '1'}, '2');
newOmg(); // "1", "2", undefined
newOmg('3'); // "1", "2", "3"
const newWtf = lol.bind({first: '1'}, '2', '3');
newWtf(); // "1", "2", "3"
Another usage is that you can pass binded function as an argument to another function which is operating under another execution context.
var name = "sample";
function sample(){
console.log(this.name);
}
var cb = sample.bind(this);
function somefunction(cb){
//other code
cb();
}
somefunction.call({}, cb);
In addition to what have been said, the bind() method allows an object to borrow a method from another object without making a copy of that method. This is known as function borrowing in JavaScript.
i did not read above code but i learn something in simple so want to share here about bind method after bind method we can use it as any normal method.
<pre> note: do not use arrow function it will show error undefined </pre>
let solarSystem = {
sun: 'red',
moon : 'white',
sunmoon : function(){
let dayNight = this.sun + ' is the sun color and present in day and '+this.moon + ' is the moon color and prenet in night';
return dayNight;
}
}
let work = function(work,sleep){
console.log(this.sunmoon()); // accessing the solatSystem it show error undefine sunmmon untill now because we can't access directly for that we use .bind()
console.log('i work in '+ work +' and sleep in '+sleep);
}
let outPut = work.bind(solarSystem);
outPut('day','night')
bind is a function which is available in java script prototype, as the name suggest bind is used to bind your function call to the context whichever you are dealing with for eg:
var rateOfInterest='4%';
var axisBank=
{
rateOfInterest:'10%',
getRateOfInterest:function()
{
return this.rateOfInterest;
}
}
axisBank.getRateOfInterest() //'10%'
let knowAxisBankInterest=axisBank.getRateOfInterest // when you want to assign the function call to a varaible we use this syntax
knowAxisBankInterest(); // you will get output as '4%' here by default the function is called wrt global context
let knowExactAxisBankInterest=knowAxisBankInterest.bind(axisBank); //so here we need bind function call to its local context
knowExactAxisBankInterest() // '10%'

Looping through array and setting visible property of instances - ActionScript3

I have variable names stored in an array, and I want to loop through array and set the visible property of that instance to false. However, I'm getting error;
Error #1056: Cannot create property visible on String.
Here is my code:
package {
import flash.events.TouchEvent;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
import flash.display.MovieClip;
import flash.events.MouseEvent;
public class touch extends MovieClip
{
public function touch()
{
var menuitems:Array = new Array("menu_One", "menu_Two", "menu_Three", "menu_Three", "menu_Four", "menu_Five");//array with instance names
for(var i:int=0;i<6;i++){
var tempName = menuitems[i];
bsF_txt.text = tempName;
trace(tempName);
tempName.visible = false;
//menu_One.visible = false;
}
}
}
}
Is. what I'm trying to do possible in AS3?
First yes it is possible!
The problem is your looping through an array of strings, not variables or anything that references a DisplayObject (maybe a MovieClip in your case?)
Assuming those strings are either instance names of MovieClips that are on your stage or vars that are referencing them you could try something like this:
public function touch()
{
var menuitems:Array = new Array(menu_One, menu_Two, menu_Three, menu_Three, "menu_Four", menu_Five);//if this gives you an error please paste some more code because these are not instance names or vars
for(var i:int=0; i<menuitems.length ;i++){ //you don't need to explicitly use 6 here you can check the menuitems arrays length
var tempName = menuitems[i]; //note, this is not needed
bsF_txt.text = tempName.name; //I think you're looking for this?
trace(tempName);
tempName.visible = false;
//menu_One.visible = false;
}
}
}
Try using the following code (I just noticed you said those are instance names...)
package {
import flash.events.TouchEvent;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
import flash.display.MovieClip;
import flash.events.MouseEvent;
public class touch extends MovieClip
{
public function touch()
{
var menuitems:Array = new Array("menu_One", "menu_Two", "menu_Three", "menu_Three", "menu_Four", "menu_Five");//array with instance names
for(var i:int=0;i<6;i++){
var tempName = menuitems[i];
bsF_txt.text = tempName;
trace(tempName);
getChildByName(tempName).visible = false;
//menu_One.visible = false;
}
}
}
}
The main change is that you need to tell flash that the string in your array is an instance name. So use getChildByName assuming they are added to to the stage.
The reason your current code is failing is because you are trying to access the visible property on a String, but String does not have a visible property. But the actually instance of that string name might.

Resources