javascriptdojo

Connect onClick listener to Dojo widget


I have the following function:

function setAccounts(data){
    var node = dijit.byId("res");
    dojo.empty("res");
    for(var i = 0; i <= data.length; i++){
        var itemWidget = new dojox.mobile.ListItem({
            id: data[i].id,
            rightText: "€ "+data[i].amount,
            moveTo: "transactions",
            label: data[i].name
        });
        node.addChild(itemWidget);
        dojo.connect(itemWidget, "onclick", getTransactions(data[i].id));
    }
}

At page loading it doesn't connect the onClick event of the new itemWidget to the function getTransactions but it simply runs that function. Where is the error ?

The data is json obtained via ajax and I've already checked that there's no error there on in json reading/parsing.


Solution

  • Dojo's 'connect' method expects an HTMLElement as the first argument. However, the dojo widgets you create are actually very specialized JavaScript objects - though they tend to make their HTMLElement available under the .domNode property.

    Actually, the easiest solution I know of would be to use the available onClick attribute inside ListItem.

    var itemWidget = new dojox.mobile.ListItem({
            id: data[i].id,
            rightText: "€ "+data[i].amount,
            moveTo: "transactions",
            label: data[i].name,
            onClick: dojo.hitch(this, 'getTransactions', data[I].id)
        });
    

    If you do end up connect-ing other events to a widget, I'd recommend writing it as itemWidget.connect(targetNode, etc - to my knowledge, that will remove event listeners if/when the widget itself is destroyed.