cn1h
cn1h

Reputation: 1248

Dijit 1.7+ widgets: how to separate event logic from the present

Basically there are two approaches to create widget instances with Dijit: Declarative and Programmatic. What I want is the mixing of the both: Setting the props like iconClass with the declarative approach, but leave the event handling to extern script block.

I tried to add the event logic directly with the dojo/on without success. I retrieved the widget with dojo/dom.byId() and dijit/registery.byId(), both don’t work. So my solution is to link the event props to a global function, something like this:

<body class="claro">
<script type="text/javascript">
    require([
        "dojo/dom",
        "dojo/on",
        "dijit/registry",
        "dijit/form/Button",
        "dojo/parser",
        "dojo/domReady!"
    ], function (dom, on, registry) {
        // both don't work
        // on(dom.byId("btn1"), "click", function () {alert("hi");});
        // on(registry.byId("btn1"), "click", function () {alert("hi");});

        // this one works
        btnClickListener = function(){alert("hi")};
    });
    // the global function
    var btnClickListener;
</script>

<button id="btn1" data-dojo-type="dijit.form.Button"
        data-dojo-props="iconClass: 'dijitIconNewTask', showLabel:false">
</button>
<button id="btn2" data-dojo-type="dijit.form.Button"
        data-dojo-props="iconClass: 'dijitIconNewTask', showLabel:false, onClick:btnClickListener">
</button>

</body>

Is there any better solution?

Upvotes: 0

Views: 571

Answers (1)

phusick
phusick

Reputation: 7352

dojo/on works, but your registry.byId("btn1") returns undefined, because in the time your code is being executed dijits have not been instantiated yet. Wrap your code into dojo/ready as you can see in this jsFiddle: http://jsfiddle.net/phusick/tRSqC/

Upvotes: 2

Related Questions