2013-07-03 33 views
0

我將小部件添加到可在此link處找到的ERSI地圖查看器項目中。Dojo - 監聽控件中的DOM dijit /表單/按鈕單擊事件

所以我用dijit/form/button做了一個查詢小部件,並且想實現一個dojo/on事件監聽器來監聽它的click事件。

該按鈕在HTML標記聲明:

<button data-dojo-type="dijit.form.Button" id="searchButton" type="button">Submit</button> 

在我的JavaScript,在postCreate函數結束時,我有:

on(dojo.byId("searchButton"), "click", function execute() { 
    // Set the WHERE search text 
    this.findParams.searchText = dojo.byId("searchText").value; 
    // Sends a request to the ArcGIS REST map service resource to perform a search based 
    // on the FindParameters specified in the findParameters argument. On completion, the 
    // onComplete event is fired and the optional callback function is invoked. 
    this.findTask.execute(this.findParams, this.showResults, this.showError); 
}); 

我收到一個類型錯誤:_526是空值。該錯誤似乎可以忽略不計,因爲我知道我做錯了。除了上面的代碼,我已經嘗試了幾十個,沒有任何工作。

我找到的所有示例dojo/on都沒有顯示如何執行此特定應用程序。

我對dojo很陌生,我只在這個項目上,直到我可以解決另一個同事遇到的問題,但是如果任何人都可以給我一個示例或鏈接到一個示例,顯示如何聽一個小部件內的DOM dijit事件將不勝感激。

ANSWER

更新的代碼之後:

我改變了代碼一點,如果旁邊的人覺得有用:

on(this.submitButton, 'click', lang.hitch(this, 'execute')); 

在哪裏執行是上市前同樣的功能,反而使這條線有點清潔。

回答

2

我假設您的查詢小部件是一個模板化小部件,也混合在WidgetsInTemplateMixin中。

http://dojotoolkit.org/reference-guide/1.9/dijit/_TemplatedMixin.html#dijit-templatedmixin

http://dojotoolkit.org/reference-guide/1.9/dijit/_WidgetsInTemplateMixin.html#dijit-widgetsintemplatemixin

並且您已經張貼的HTML是在widget模板。你最好的選擇是不使用ID。通過使用ID,您只能在頁面上擁有這些小部件中的一個。這對你的用例可能沒問題,但不是一個好的做法。相反,請使用data-dojo-attach-point

<div> 
    ... MORE HTML... 
    <button data-dojo-type="dijit.form.Button" 
     data-dojo-attach-point="submitButton" type="button">Submit</button> 
</div> 

在你的代碼,然後你可以參考submitButton作爲窗口小部件的變量。

on(this.submitButton, "click", function execute() { 
    ... 
} 
+0

嗨,感謝您的評論。發佈問題時,這是我的錯誤。該代碼實際上使用了您突出顯示的正確的html代碼。更新了問題以反映這一點。 –

+0

更新了我的答案。 –

+0

你是對的,它是一個模板化的小部件,可以在WidgetsInTemplateMixin中混合使用。你的答案是現貨,並且工作得很好。感謝您的解釋。 –

0

由於您的按鈕本身是一個小部件,因此您不需要dojo/on來攔截點擊事件。

假設你把你的小部件的依賴性列表「的dijit /註冊表」,嘗試:

registry.byId("searchButton").on("click", function execute() { 
    // Set the WHERE search text 
    this.findParams.searchText = dojo.byId("searchText").value; 
    // Sends a request to the ArcGIS REST map service resource to perform a search based 
    // on the FindParameters specified in the findParameters argument. On completion, the 
    // onComplete event is fired and the optional callback function is invoked. 
    this.findTask.execute(this.findParams, this.showResults, this.showError); 
}); 

爲什麼你用錯誤的原因是因爲當你這樣做......

<button data-dojo-type="dijit.form.Button" id="searchButton" type="button">Submit</button> 

...您創建一個id爲「searchButton」的小部件。雖然節點本身在呈現小部件模板時不再具有該id。因此你不能通過dom.byId來引用它。

如果你想widget的れ一個參考,你需要做的:

registry.byId("searchButton").domNode 

如果你看一下this fiddle,你會看到按鈕れ沒有一個ID在所有。如果現在您在Firebug或瀏覽器控制檯中查看該按鈕的html,您將注意到domNode具有屬性「widgetid = btn2」而不是「id = btn2」。