开发者

How can I programatically provide a JS event handler with references to additional HTML elements?

开发者 https://www.devze.com 2022-12-21 13:14 出处:网络
Say, I have two HTML elements - an input field and a button. The code for both 开发者_Go百科is generated programatically.

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

The code for both 开发者_Go百科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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消