Appcelerator - Javascript - 丢失参考
Appcelerator - Javascript - losing the reference
我的应用程序中有以下代码来添加小部件:
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++;
}
所以我可以在我的 scrollview
上添加 mooncards
并添加一个要在小部件内部触发的功能以删除它自己。
这是个主意,但不幸的是,唯一删除的小部件是最后一个。很明显,引用 remove(mooncards[i])
在添加新小部件时丢失了。
我还在学习 Javascript,所以我不知道我做错了什么。
如何在不丢失引用的情况下添加很多小部件并具体删除每个小部件?
请让我知道如果我需要更清楚。
您遇到了典型的 javascript 绑定问题。
我会尝试改变:
$.dashboard_scroll.remove(mooncards[i].getView());
至
$.dashboard_scroll.remove(this.getView());
您可以使用 bind
:
mooncards[i].on('close',function(){
$.dashboard_scroll.remove(this.getView());
}.bind(mooncards[i]));
bind
将用您提供给函数的第一个参数替换函数中的 this
。考虑这个例子:
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')();
如果您的用户使用的是 IE8 及以下版本,您将需要使用上面 link 中提供的 polyfill。
我的应用程序中有以下代码来添加小部件:
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++;
}
所以我可以在我的 scrollview
上添加 mooncards
并添加一个要在小部件内部触发的功能以删除它自己。
这是个主意,但不幸的是,唯一删除的小部件是最后一个。很明显,引用 remove(mooncards[i])
在添加新小部件时丢失了。
我还在学习 Javascript,所以我不知道我做错了什么。
如何在不丢失引用的情况下添加很多小部件并具体删除每个小部件?
请让我知道如果我需要更清楚。
您遇到了典型的 javascript 绑定问题。
我会尝试改变:
$.dashboard_scroll.remove(mooncards[i].getView());
至
$.dashboard_scroll.remove(this.getView());
您可以使用 bind
:
mooncards[i].on('close',function(){
$.dashboard_scroll.remove(this.getView());
}.bind(mooncards[i]));
bind
将用您提供给函数的第一个参数替换函数中的 this
。考虑这个例子:
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')();
如果您的用户使用的是 IE8 及以下版本,您将需要使用上面 link 中提供的 polyfill。