Adding events after swap

211 views
Skip to first unread message

thescented...@gmail.com

unread,
Nov 18, 2016, 2:58:27 AM11/18/16
to intercooler-js
Hi, I'm new to intercooler so this might be a really stupid question. How would I wire in my own event listeners for some html returned by intercooler?

For example if I had:

<a ic-get-from="/some-list">Get List</a>

where /some-list returns, say, this:
<ul>
<li class="my-item" data-id="1">One</li>
<li class="my-item" data-id="2">Two</li>
</ul>

How would I wire in something like:
$(".my-item").click(function(evt) { alert(evt.target.getAttribute("data-id");});

I've tried using the complete.ic and after.success.ic events and X-IC-Trigger but everything seems to run *before* the new elements are swapped in so jquery never attaches the click event... As far as I can see ic-action only works for jquery actions on the target element so I'm not sure that would work either.

I looked through the source and managed a quick workaround by adding this to the processICResponse function:
try {
doSwap();
target.trigger("swap_complete.ic", [target]);
} catch (e) {
log(elt, "Error during content swaop : " + formatError(e), "ERROR");
}

but obviously I'd rather not touch the actual intercooler source.

Like I said this is probably a dumb question - is there an idiomatic way of handling this case?

Really enjoying the library so far, thanks for coming up with something so simple!

Carson Gross

unread,
Nov 18, 2016, 11:06:20 AM11/18/16
to intercooler-js, thescented...@gmail.com
Hi,

You’ve got a few of options, listed here in increasing complexity:

First, if your action is simple enough, you could use the ic-action attribute: 


Secondly, you could set up an intercooler ready function (similarl to $.read()):

  Intercooler.ready(function(elt) {
    $(elt).find(".my-item").click(function(evt) { alert(evt.target.getAttribute("data-id");}); 
  });

Finally, you could use the regular jQuery ready function, but make the handler dynamic:

  $(function() {
    $( “body" ).on( "click", ".my-item", function() {
      alert(evt.target.getAttribute("data-id");
    });
  }

All of these are fine.  The first option is the most intercoolery and the last one is the most flexible, so your call.

Glad you are finding intercooler useful!

Cheers,
Carson
LeadDyno • Co-Founder
@carson_gross
--
You received this message because you are subscribed to the Google Groups "intercooler-js" group.
To unsubscribe from this group and stop receiving emails from it, send an email to intercooler-j...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

thescented...@gmail.com

unread,
Nov 21, 2016, 1:03:11 AM11/21/16
to intercooler-js, thescented...@gmail.com
Awesome, thanks!
Reply all
Reply to author
Forward
0 new messages