2015-08-25 14 views
0

我正在開發一個簡單的Firefox插件,用於統計一個頁面中元素的實例數與某些條件匹配(例如。name =「btnK」)並顯示它在側邊欄上。Firefox插件開發:腳本之間的通信 - >變量沒有更新

如果我理解正確,與頁面的DOM的互動,我必須使用port.emit/port.on和內容腳本,所以我這樣做:

1)sidebar.js腳本發出一個信號index.js(主插件腳本)請求「實例計數」; 2)index.js發出一個信號給內容腳本(countScript.js),該腳本附着在對實例進行計數的頁面上(並且效果很好); 3)countScript.js使用請求的數字發出對index.js的響應; 4)index.js發出答案(「instancesCounted」,n)和sidebar.js監聽它(addon.port.on(「instancesCounted」),function(n){..});

我通過console.log測試了所有這些段落,它們都工作(數字總是匹配頁面上的元素),但是我必須使用該數字(我們稱之爲「currI」)將其打印在側邊欄。當我嘗試這樣做時,它顯示currI未定義。我認爲這是一個範圍問題,並試圖使用全局變量,但也沒有工作。

有什麼建議嗎?

下面是一些代碼:

sidebar.js:

var currI = 0; 

function printInstances(){ 
    elName = $("#inputNewLoc").val(); // just get the element name in order to count it later 
    currI = countInstances(elName); // from here currI is undefined  
    console.log("currI", currI); 
    [..] 
} 

function countInstance(elName){ 
    currI = addon.port.emit("countInstances", elName); 
    console.log(currI); // here shows correctly the number of istances 
} 

index.js

var sidebar = require("sdk/ui/sidebar").Sidebar({ 
id: 'my-sidebar', 
title: 'My sidebar', 
url: self.data.url("sidebar.html"), 

onAttach: function(worker) {  
    worker.port.on("countInstances", function(elName){  
    var worker2 = tabs.activeTab.attach({ 
     contentScriptFile: self.data.url("countScript.js") 
    }); 
    worker2.port.emit("execCount", elName); 
    worker2.port.on("instancesCounted", function(n){   
     worker.port.emit("instancesCounted", n); 
     console.log(n); // n is the correct number of instances here  
    })    
    })  
} 

countScript.js

self.port.on("execCount", function(elName) { 
    var elements = document.getElementsByName(elName); 
    n = elements.length; 
    self.port.emit("instancesCounted", n); // all seems to work fine here 
}); 
+0

你在腳本間發生了所有這些異步'emit'和'on' - 但不知何故,你只能簡單地使它工作並期望(不正確)'addon.port.emit'在一個同步中地方,但不是其他人 - 我看不出正確的數字可能會顯示在哪裏,你說它是在'sidebar.js' ...我認爲你錯了 - 你在哪裏通過計數的例子到' sidebar.js' –

+0

@Jaromanda我想我得到了異步通信的基本概念,並且port.on/emit是傳遞數據的異步方法。 事實上,我嘗試了一些變體,直到我得到我發佈的一個, 你是對的我忘了複製sidebar.js的一部分: 'addon.port.on(「instancesCounted」,function(n){ currI = n; console.log(currI)//這裏的數字是正確的 })' 我不明白的是爲什麼currI結束未定義,而不是= 0; btw謝謝你的幫助! –

+0

因爲這一行'currI = countInstances(elName);'和'function countInstance'沒有返回任何東西(即返回值是** undefined **),所以它結束了未定義。 –

回答

0

我的建議對sidebar.js:

var currI = 0; 

function printInstances(){ 
    elName = $("#inputNewLoc").val(); // just get the element name in order to count it later 

    addon.port.on("instancesCounted", function(n){ do something with n 
     console.log("n", n); // 
    }); 

    addon.port.emit("countInstances", elName); 
} 
+0

你真的幫助了我!如你所說,焦點是port.on/emit的「異步性」。非常感謝你! –