NewToMS
NewToMS

Reputation: 65

binding functions with objects to jQuery 'change' event handler

When you specify a function (with or without parameters) in the DOM via onChange, you are limited to static paramters. E.g.

<select id="blah" onChange="doSomething(3);">

However, jQuery lets you dynamically define and assign functions to event handlers, such as 'change'.

See the example below:

function addRow(customObject) {
  << Create TR containing a select named "#someSelect + customObject.id" >>

  // Demo
  $("#someSelect" + customObject.id).change(function() {
    changeSomething(customObject)
  });
}

My question is - essentially - will this work? I am using a specific instance o f an object in my jQuery change event handler. Will that particular instance of customObject (wherever it lies) always be bound to this event handler callback?

customObject is initialized at load, and is one of many. For that particular select box, I always want it to be linked to that object.

New to jQuery. Thanks in advance.

EDIT:

I have several rows of items. Each is represented by an object. I just want to make sure that when someone modifies one of the rows via HTML, that the underlying object (bound to the callback function) is properly updated.

I am looking for something like this, conceptually a mapping between:

Row 1 - customObject1
Row 2 - customObject2
Row 3 - customObject3

... such that if I modify one of the HTML elements (e.g. change the select box) in row 3, that behind the scenes, customObject3 is modified

Upvotes: 0

Views: 81

Answers (1)

Jakub Kotrs
Jakub Kotrs

Reputation: 6229

What you have will work in case customObject.id is defined before adding the listener and you intent the listener itself to be bound to that specific element without moving it around.

From your question I understand that customObject.id is dynamic as in can change its value and depending on this value, the listener can listen on different element. In this case, you'd have to use a bit more general selector and check the value inside the listener itself:

$('select').on('change', function(e) {
    if(this.id === 'someSelect' + customObject.id)
        return myCallback(e);
});

Edit:

The problem lies in accessing the customObject inside the listener. It uses the current content, not the content it used to have when you added the listener.

Easiest solustion I know is:

var select = $("#someSelect" + customObject.id);
select.customObject = customObject; /* save customObject to the select itself */
select.on('change', function() {
    changeSomething(this.customObject); /* don't use global object but its own */
});

Upvotes: 1

Related Questions