Ganesh K
Ganesh K

Reputation: 3

How to get the element reference "this" in EmberJS events?

I want to access the target element in the called method in onchange. I have the following code:

Template

<select class="form-control" data-abc="1" onchange={{action 'someMethod' value="target.value"}} >
  <option value="">Select</option>
  .
  .
  .
</select>

Component

export default Ember.Component.extend({
    actions: {
      someMethod(value) {
        jQuery(this).data("abc"); // <-- Want to access element here
      }
    }
});

But, this doesn't work.

Upvotes: 0

Views: 577

Answers (2)

Ganesh K
Ganesh K

Reputation: 3

I got the answer:

<select class="form-control" data-abc="1" onchange={{action 'someMethod' value="target"}} >
  <option value="">Select</option>
  .
  .
  .
</select>

As can be seen in above code, we can pass the target instead of target.value. Then wrap target in jQuery to access desired data attribute.

Upvotes: 0

Ember Freak
Ember Freak

Reputation: 12872

When you use value="target.value", someMethod will receive only the value alone and it will not receive default event object.

onchange={{action 'someMethod'}}

your component code would be,

export default Ember.Component.extend({
    actions: {
      someMethod(event) {
        //its event object, you can access event.target to get element or event.target.value to get the value.
      }
    }
})

Upvotes: 1

Related Questions