Simple text messaging - only last button works, while not above it

15 views
Skip to first unread message

Nirmit Goyal

unread,
Feb 28, 2017, 11:50:31 PM2/28/17
to EasyRTC
Github link to project: https://github.com/nirmitgoyal/Collaborate-It

I am using easyrtc in my django (with front end in jQuery ) application. I tried out instant_messaging, but the easyrtc could send data to only last list(button).
What might be the issue?
Someone please help.

Thanks

Eric Davies

unread,
Mar 1, 2017, 12:25:05 AM3/1/17
to EasyRTC
When someone says "only my last button works", its usually the case that they didn't understand how closures work in Javascript. You need to read about immediately-invoked-function-expressions . If you are using typescript, using a let statement instead of a var statement can be an easier solution.

Nirmit Goyal

unread,
Mar 1, 2017, 1:45:55 AM3/1/17
to EasyRTC
I read about it, but how will it solve the problem of that just the last
button.onclick is working.... ?

Eric Davies

unread,
Mar 1, 2017, 2:09:37 AM3/1/17
to EasyRTC
The assumption is that you've got a block of code that looks like this

function buildbuttons() {
   var some_id;
   for( some_id in somelist ) {
       var button = document.createElement("button");
       button.onclick = function() {
             send_message_to( some_id );
       }
       some_panel.appendChild(button);
   }
}

All the button onclick methods share the same some_id variable, which will be the last value assigned to some_id.
immediately-invoked-function-expressions are how you capture the current value  (at the time of the loop iteration) of some_id in the closure so each button references the value you expect it to.


Reply all
Reply to author
Forward
0 new messages