2014-07-01 28 views
0

通常,分配功能到道場對象的情況下,我們使用數據道場-附加事件如示於下面的代碼:動態分配現有函數來動態創建的道場對象

<div data-dojo-type="dijit/TitlePane" data-dojo-attach-event="toggle: getServiceTypes" open="false" title="Filter by Service Type"></div> 

現在,與地方在道場的聲明函數,我有以下幾點:

getServiceTypes: function(){ 
    //do some javascript function here 
} 

現在,我該如何使用相同的功能(getServiceTypes)連接到一些動態創建的對象:

var tp = new dijit.TitlePane({ 
     open:false, title: response.rows[index].name, 
     id: response.rows[index].name}); 
dojo.connect(tp,"toggle",function(){//do some more javascript function here}); 

我用以下,但仍遇到錯誤:

dojo.connect(tp,"toggle",getServiceTypes); 
dojo.connect(tp,"toggle","getServiceTypes"); 
dojo.connect(tp,"toggle",function(){getServiceTypes()}); 

我怎麼能重複使用getServiceTypes功能到我的動態創建的對象?

TIA

回答

0

這應該工作得很好,但是,還需要你TitlePane附加到DOM節點,例如:

dojo.require("dijit.TitlePane"); 
dojo.addOnLoad(function() { 
    var tp = new dijit.TitlePane({ 
     open:false, 
     title: "Title", 
     id: "myTitlepane" 
    }, "myTitlepane"); // Specify the ID of the DOM node 
    dojo.connect(tp,"toggle",function(){ 
     console.log("Toggled"); 
    }); 
}); 

或者:

dojo.require("dijit.TitlePane"); 
dojo.addOnLoad(function() { 
    var tp = new dijit.TitlePane({ 
     open:false, 
     title: "Title", 
     id: "myTitlepane" 
    }); 
    dojo.connect(tp, "toggle", function(){ 
     console.log("Toggled"); 
    }); 
    dojo.place(tp.domNode, "myTitlepane"); 
}); 

由於你也可以看到JSFiddle工作正常:http://jsfiddle.net/4JRAW/


但是,toggle()函數並不是一個真正的事件,所以我不知道連接它是否是個好主意。一個更好的解決辦法是連接到onShowonHide事件,例如:

var toggleFunction = function(){ 
    console.log("Toggled"); 
}; 
dojo.connect(tp, "onShow", toggleFunction); 
dojo.connect(tp, "onHide", toggleFunction); 
tp.startup(); 

此外,使用startup()功能將需要觸發這些事件處理程序。


從道場1.7及更高版本,舊的模塊加載器已被棄用,dojo/connect太多,所以則建議如下:

require([ "dijit/TitlePane", "dojo/domReady!" ], function(TitlePane) { 
    var tp = new TitlePane({ 
     open:false, 
     title: "Title", 
     id: "myTitlepane" 
    }, "myTitlepane"); 
    var toggleFunction = function(){ 
     console.log("Toggled"); 
    }; 
    tp.on("show", toggleFunction); 
    tp.on("hide", toggleFunction); 
    tp.startup(); 
});