Thursday, May 4, 2017

BACKBONE: Detecting Events for Several Elements

Problem:
Suppose you have several "select" elements in a table with the same data that triggers another "select" element, but you want to detect each "select" individually.

<table>
  <tr>
    <td><select>.....</select></td> <!--Select we want to detect-->
    <td><select>.....</select></td> <!--Dependent Select--> 
 </tr>
 <tr>
    <td><select>.....</select></td> <!--Another Select-->
    <td><select>.....</select></td> <!--Another dependent Select-->
 </tr>
</table>

Solution:
In Backbone, we can add the "data-id" tag to the select element and dynamically populate the id in Backbone. Also, we need to add a class tag so all the "select" elements are fired without the need to construct a map or array of events. In the event you want to favor performance over simplicity, please consider the events collection approach.

({
     selectTable1:
    {
         selectCounter : 0
    },

    initialize: function()
    {
         // Add selects dynamically here (or create a helper function),
         // or get other selects, etc.
    },
 
    events:
   {
       'change .myClass': 'detectEvent'
   },

   detectEvent: function(e)
    {
        e.preventDefault();
        var id = $(e.currentTarget).data("id");
    }
)}

No comments:

Post a Comment