2014-02-18 68 views
3

我有dojo自定義小部件。自定義事件不在dojo小部件上觸發

我需要從定製窗口小部件, 發射事件此,我已添加的事件偵聽器

<!DOCTYPE html> 
<html> 
<head> 
    <title></title> 
    <script type="text/javascript"> 
     var dojoConfig = { 
      async: true, 
      parseOnLoad: true, 
      isDebug : true, 
      packages:[ 
       { name:"custom", 
        location:"/Test/js" 
       } 
      ] 
     }; 
    </script> 
    <script src="//localhost:8080/dojo1.9.0/dojo/dojo.js"></script> 
</head> 
<body> 
<script> 
    require(["custom/MyWidget","dojo/on","dojo/dom-construct","dojo/_base/window","dojo/domReady!"],function(MyWidget,on,domconstruct,window){ 
     var mywidget = new MyWidget(); 
     mywidget.startup(); 
     domconstruct.place(mywidget.domNode,window.body(),"after"); 


     on(mywidget,"customevent",function(data){ 
      console.log(" received notification "+data); 
     }); 
    }); 
</script> 
</body> 
</html> 

和插件如下

define([ 
    "dojo/_base/declare", 
    "dijit/_WidgetBase", 
    "dijit/_OnDijitClickMixin", 
    "dijit/_TemplatedMixin", 
    "dojo/text!./widget.html", 
    "dojo/on", 
    "dojo/_base/lang" 
], function (declare, _WidgetBase, _OnDijitClickMixin, _TemplatedMixin, template,on,lang) { 

    return declare([_WidgetBase, _OnDijitClickMixin, _TemplatedMixin], { 
     templateString: template, 
     //  your custom code goes here 
     _onClick:function() 
     { 

     }, 

     postCreate : function() 
     { 
      on(this.searchtextbox,"click",lang.hitch(this,"sendEvent")); 

     }, 
     sendEvent : function(event) 
     { 
      console.log("Click event in widget "+event); 
      this.emit("customevent",event.x) 
     } 
    }); 

}); 

//Widget.html

代碼
<div class="${baseClass}" data-dojo-attach-point="searchtextbox"> 
    <p> 
     here your widget 
    </p> 
</div> 

問題是行

this.emit("customevent",event.x)拋出錯誤

回答

5

小部件事件

你不應該使用dojo/on將事件處理程序添加窗口小部件,它僅適用於DOM節點。如果從dijit/_WidgetBase擴展(像你這樣做),然後有一個方法叫on(),您可以使用,例如:

myWidget.on("customevent", function(data) { 
    console.log(" received notification "+data); 
}); 

的Widget擴展點

我不知道什麼emit()功能確實,但似乎這是問題所在。根據the docs,您應該使用普通函數編寫擴展點。例如:

postCreate : function() { 
    on(this.searchtextbox,"click",lang.hitch(this, "_onClick")); 
}, 
_onClick: function(event) { 
    // This is where you put your code 
    console.log("Click event in widget "+event); 
    this.onCustomEvent(event.x); 
}, 
onCustomEvent: function() { 
    // This can be left empty, it will be used as the extension point 
} 

在這種情況下,你的點擊事件到_onClick()功能,進而調用onCustomEvent()以正確的參數綁定。這個函數是公用的,可以用來綁定自定義事件處理程序。

這裏是full example

+0

我已經改變收聽代碼如下'code'mywidget.on( 「自定義事件」,功能(數據){ 的console.log( 「接收到的通知」 +數據); });'code'仍然沒有工作:( – chiranjeevigk

+0

看起來'emit()'函數會拋出一個錯誤,我不確定那個函數的功能,但是在文檔中他們使用了不同的方式來創建自定義事件。與一個小的howto。 – g00glen00b

1

發射方法的第二個參數應該是一個對象,但我沒有發送對象。

sendEvent : function(event) 
     { 
      console.log("Click event in widget "+event); 
      this.emit("customevent",**event**) 
     }