views:

26

answers:

1

Say, I have two HTML elements - an input field and a button.

The code for both is generated programatically.

After I generate the code, I have a function that binds event handlers to those elements.

//Locate add to order button and bind event handler to it
this.input_add = document.getElementById("add_to_order");
this.input_add.onclick = 
    function () {
        return controller.addToOrder.call(controller);
    };

// Locate quantity input and bind event handler to it
this.input_quantity = document.getElementById("form_quantity");
this.input_quantity.onkeyup = 
    function () {
        return controller.changeQuantity.call(controller, this);
    };

Here's the puzzle - controller.changeQuantity requires a reference to this.input_add.

As far as I can tell, I can't pass this.input_add into the call parameter list for controller.changeQuantity.

I've found only one solution - putting a reference to this.input_add in the this.input_quantity object.

this.input_quantity.addButton = this.input_add

Are there any alternatives? Is this a good practice? I'm trying to keep my application as decoupled as possible.

A: 

Add your DOM objects to your "controller", and set up your event handlers as part of that object, something like:

var controller = { ... };
controller.input_add = document.getElementById("add_to_order");
controller.input_quantity = document.getElementById("form_quantity");

controller.input_add.onclick = function() { controller.addToOrder.call(controller, this);}

Then you can reference these DOM elements from within your controller object at any point.

I often set up references to DOM elements, register event handlers, etc. in the setup code for my main Javascript controller object.

Trent Davies
That was my unitial design, but I've consciously moved away from it - it required me to maintain references to those objects both in the "Rendering" functions, as well as the "Controller" (Or alternatively, after generating the code, I'd have to perform binding of event handlers in the controller). I don't want the controller to be too tied down to the implementation of the UI - hence, no "document.getElementByID" calls in it - I feel that breaks encapsulation, by giving the controller too much knowledge about the details of the UI.
Vladislav