简体   繁体   中英

Appcelerator - Javascript - losing the reference

I have the following code on my app to add widgets:

while(i < rc_length) {
    console.log(i);
    mooncards[i] = Alloy.createWidget("moonCards");
    mooncards[i].on('close',function(){
        $.dashboard_scroll.remove(mooncards[i].getView());
    });
    $.dashboard_scroll.add(mooncards[i].getView());
    i++;
}

So I can add mooncards on my scrollview and add a function to be triggered inside the widget to remove itself.

That was the idea, but unfortunately the only widget removed is the last one. Clearly the reference remove(mooncards[i]) is lost while adding new widgets.

I'm still learning about Javascript, so I don't what I'm doing wrong here.

How can I add a lot of widgets and remove each one specifically, without losing the reference?

Please, let me know If I need to be more clear.

You have a classic javascript binding issue.

I would try changing:

 $.dashboard_scroll.remove(mooncards[i].getView());

to

 $.dashboard_scroll.remove(this.getView());

You can use bind :

mooncards[i].on('close',function(){
    $.dashboard_scroll.remove(this.getView());
}.bind(mooncards[i]));

bind will replace this in your function with the first parameter that you give to it. Consider this example:

x = function() { console.log(this); }

// outputs the window context if running in browser
// because the value of 'this' is the context where
// where the function was executed
x(); 


// outputs a String object, 'hello' because the value of
// this has now been bound to the string 'hello'
x.bind('hello')();

If your users are in IE8 and below, you will need to use the polyfill provided in the link above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM