2016-08-09 65 views
1

我有我的應用程序下面的代碼添加小工具:Appcelerator的 - 使用Javascript - 失去了參考

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++; 
} 

所以我可以在我的scrollviewmooncards並添加功能部件內被觸發,除去本身。

這是想法,但不幸的是,唯一移除的部件是最後一個。顯然,在添加新小部件時,參考文獻remove(mooncards[i])已丟失。

我還在學習Javascript,所以我不會在這裏做錯。

如何添加很多小部件並專門刪除每個小部件,而不會丟失參考?

請讓我知道如果我需要更清楚。

回答

0

你有一個經典的JavaScript綁定問題。

我會嘗試改變:

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

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

完美的作品!謝謝您的幫助! – pasf

0

您可以使用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及以下,你將需要使用上面的鏈接提供的填充工具。