bind attribute in custom event

57 views Asked by At

In Sugarcrm (backbone.js) I am trying to get custom attribute (user_id) from List (in .hbs file)

  <div class='dropdown usersLegend'>
            <ul class='dropdown-menu'></ul>
        </div>

and bind data dynamically like

    _.each(data.users, function (user) {
    list += '<li user_id="' + user.id + '"> ... </li>';
    });
   
     this.$('.usersLegend ul').html(list);

I made custom event in initialize

  this.events = {
        'click li': 'getselectedUser',
        };

and in method, i tried the following code

    let currentTarget = JSON.stringify(e.currentTarget);
    if (currentTarget != null) {

    var doc = new DOMParser().parseFromString(currentTarget, "text/xml");
    var tmpDiv = doc.createElement('div');
    tmpDiv.innerHTML = currentTarget;

    var links = tmpDiv.getElementsByTagName('li');
    [...links].forEach((link) => {
    console.log(link.getAttribute('user_id'));
    });


    }

this way I am not getting user_id value, how can i bind user_id in custom event

1

There are 1 answers

0
Julian On

The .hbs extension refers to Handlebars, which is a template language. This means that you can insert the user IDs right in the .hbs file:

<div class='dropdown usersLegend'>
    <ul class='dropdown-menu'>
        {{#users}}
        <li data-user-id="{{{id}}}"> ... </li>
        {{/users}}
    </ul>
</div>

... without having to write the _.each loop, if you write the render method of your view as follows:

this.$el.html(this.template(data));
return this;

How this works:

  1. The data object that contains the users array is passed to the compiled template.
  2. The compiled template iterates the users array inside the {{#users}}...{{/users}}. (This is a notation that Handlebars inherited from Mustache (more up-to-date language reference here). You could also use the notation {{#each users}}...{{/each}}, which is specific to Handlebars.)
  3. For each user object, the template writes a <li> tag with the user ID inserted in an attribute. Note that I use data-user-id rather than user_id as the attribute name; the data− prefix has a special meaning to the browser and to jQuery, so this notation is more likely to work. The {{{id}}} notation means "take the id attribute of the current object (which is the current user) and interpolate it in the template output without escaping" ({{id}} would do the same thing but with escaping).
  4. The template returns the generated HTML as a string, which becomes the live HTML of your view through this.$el.html(). I presume this last part is currently already happening in your code.

Now, what remains is to take out the user ID after the 'click' event. For this, event.target (not event.currentTarget) and jQuery's .data method are your friends:

var clickedItem = $(event.target);
var userId = clickedItem.data('user-id');
// Do whatever you need with the user ID...
console.debug(userId);