2013-10-06 52 views
2

我想使用由Strust2 jQuery插件內部使用的publish/subscribe框架。使用Struts 2 jQuery插件發佈事件

用戶可以從列表中選擇一個帳號或在文本框中鍵入它。

我想在文本框或選擇選項更改時發佈事件。所以,用戶只能鍵入文本框或從選擇框中選擇一些東西:

<s:textfield name="account" onblur="$.publish('accountChanged',this,event)"/> 
<s:select name="accountList" list="destinationAccounts" 
    onblur="$.publish('accountChanged',this,event)"/> 

以下是JS:

$.subscribe('accountChanged', function(event, data) { 
    alert("New data is: " + data.value); 
    if (event.target.id=='account') { 
     //Do something 
    } 
} 

這裏有問題:

  1. 數據。值僅適用於文本框,對於選擇框data.value未定義。
  2. 我想知道哪個目標收到事件。 event.target.id不工作!我認爲事件對象不是一個jQuery事件對象?

我回顧了示例展示應用程序,但找不到任何。

我是否正確調用$.publish方法?有更好的方法嗎?

回答

2

如果您訂閱了主題,請將每個標籤的主題名稱保持爲唯一,以允許爲標籤分隔處理程序。每次在onblur事件中發佈主題時都會創建新事件。主題的textfield處理程序如您所描述的那樣工作。 select標記不起作用,因爲錯誤的參數作爲data傳遞。的工作代碼

<s:textfield name="account" onblur="$(this).publish('accountChanged', this, event)"/> 
<s:select name="accountList" list="{'list1', 'list2','list3'}" onblur="$(this).publish('accountListChanged', this, event)"/> 
<script type="text/javascript"> 
    $.subscribe('accountChanged', function(event, data) { 
    alert("accountChanged: " + data.value); 
    }); 
    $.subscribe('accountListChanged', function(event, data) { 
    alert("accountListChanged: " + data.parentElement.value); 
    }); 
</script> 

正如你可以看到data.value的例子是不確定的,因爲data.parentElement.value應該被使用。 event.target.id不工作,因爲應該使用event.originalEvent.target.idevent對象是一個jQuery事件,但originalEvent是DHTML對象,它是blur

我不知道你的要求,如果你需要訂閱/發佈事件或使用原始事件處理程序,我不能說在這種情況下有什麼更好的。

+0

要求很簡單。 頁面中有一個隱藏的文本字段。該隱藏文本的值應設置如下: 如果用戶在文本字段中鍵入一個值,則應該使用文本字段值設置隱藏字段值。 如果用戶從選擇輸入中選擇帳戶,則應從所選選項中設置隱藏字段值。 我認爲當文本框發生變化時以及用戶從選擇列表中選擇一些內容時,我必須發佈'accountChanged'主題。這是我發佈相同的主題名稱的方式。然後在訂閱方法中,我想通過讀取數據來設置隱藏值。值 –

+0

好吧,你知道該怎麼做嗎? –

+0

是的!你的回答引導了我很多。我會爲其他人提供答案 –

0

下面的代碼解決了我的問題:

,因爲我無法找到發佈/訂閱框架的任何例子,我希望下面的例子可以幫助別人!

將JSP是

必須調用${this).publish$.publish

<s:textfield name="account" onblur="$(this).publish('destinationChanged', this, event)"/> 
<s:select name="accountList" list="{'list1', 'list2','list3'}" onblur="$(this).publish('destinationChanged', this, event)" emptyOption="true"/> 
<s:textfield name="destinationAccount" type="hidden" /> 

而且JS會

$.subscribe('destinationChanged', function(event, data) { 
      //If user types in the textbox 
      //then get the value and make the select box shows an empty option 
     if(!!data.value){ 
      destinationAccount= data.value; 
     $('#destinationKnownAccount').val($("#destinationKnownAccount option:first").val()); 
     } else{ 
      //The user selected an account from select box. 
      // So get the value from select box and clean textbox   
      destinationAccount= data.parentElement.value; 
      $('#destinationUnknownAccount').val(''); 
     } 
      //Set the hidden box   
     $('#destinationAccount').val(destinationAccount); 


    }); 

如前所述可以使用event.originalEvent.target.id找到其目標是選擇。