Getting the value of element clicked on in Emberjs

175
November 21, 2016, at 7:41 PM

I have a series of labels that I would like to retrieve the text from when the user clicks on them. I thought the jquery might be doable in Emberjs:

$(this).attr('text');

This however, doesn't work with Ember. My component view is this:

<ul class="list-inline">
  {{#each model as |model|}}
    <li {{action "sendToInput"}} class="label label-default">{{model.name}}</li>
  {{/each}}
</ul>

I would like to retrieve that model.name value via the action "sendToInput".

In my component js file I have tried:

actions: {
  sendToInput() {
    $(this.target).attr('text');
  }
}

I have also tried:

this.innerHTML;
$(this).text();
this.get('text');
$(this).val();

I have also opened up the console and dug through this and cannot seem to find where they store the element clicked on.

The documentation doesn't mention this and there's no issue I can find on the Github for ember-cli.

Thanks.

Answer 1

The common way is to pass a model name as an action parameter like this:

<ul class="list-inline">
  {{#each model as |model|}}
    <li {{action "sendToInput" model.name}} class="label label-default">{{model.name}}</li>
  {{/each}}
</ul>

and then handle it in the action:

actions: {
  sendToInput(name) {
    // do something with name
  }
}

But if you still need to access the exact element's html, there is another workaround:

export default Ember.Component.extend({
    didInsertElement () {
        this.$().on('click', '.label', function (event) {
            $(this).text();
        })
    }
});
READ ALSO
Is there a way to target the button on screen?

Is there a way to target the button on screen?

I have this fancy code from http://t4t5. github.

226
CodeIgniter dynamic input with jquery and insert to database

CodeIgniter dynamic input with jquery and insert to database

I stumbled upon a concern regarding my friends CI project: he wanted to add a new <input> tag to the body and insert to MySQL, so I made this code:.

446
Modify Arrow Key Navigation to support Mobile Swipe

Modify Arrow Key Navigation to support Mobile Swipe

I currently use the code below to navigate to the next and previous pages by allowing the user to use the left and right buttons. How would I integrate the code for swiping on the mobile phone for navigation?.

236