Maximus S
Maximus S

Reputation: 11095

Basic questions about javascript

Please take a peek at the following code, which is in _form.html.erb:

<script>
    function typeCatch(){
      $.post("<%= update_readers_link_essay_path(@essay) %>");
      $(this).off("keypress", typeCatch);//remove handler
     }

  $(function(){
    ("form#new_revision").on("keypress", typeCatch);
  });
</script>

When the user starts typing in a form, the ajax request should be fired and update the readers list. However, the post request is not fired when I start typing in the form and I am trying to debug this problem.

Since I am not that familiar with javacsript yet, I would appreciate if you helped me clarify a few things.

a. For the second part, can I just do

$("form#new_revision").on("keypress", typeCatch);

without wrapping it with $(function() {} ?

b. Is there anything that I'm doing wrong? Since ajax call isn't fired, I must have made a mistake in the second part?

Additional Question

my_personal_chat.js (in app/assets/javascripts pipeline)

$(function() {
  var pusher = new Pusher('app_key');
  var channel = pusher.subscribe('presence-my-chat');

  channel.bind('pusher:subscription_succeeded', function(members) {
    $('#online_users').empty();
    members.each(function(member){
        addMember(member);
    });
... other functions ...
});

This is how I implemented my chat feature, using Pusher. Since the channel is private, everytime I call var channel, an ajax call to POST /pusher/auth is invoked.

I found that every time I navigate to a different page, even when it's not where the chat feature is, POST /pusher/auth is called. Basically, every time my_personal_chat.js is loaded, the ajax call will be unnecessarily invoked.

Question: How do I prevent this from happening? my_personal_chat.js should only be loaded when I go to myapp.com/chat. Should I just pull out everything from the javascript file and put it inside chat.html.erb? Is that the conventional way of doing it?

to answer my own question: I moved the code from my_personal_chat.js to chat.js.coffee and deleted my_personal_chat.js. Now the javascript only gets loaded when users go to the chat page.

Upvotes: 0

Views: 233

Answers (1)

Barmar
Barmar

Reputation: 780889

a. There are alternatives, but wrapping the code in $(function() {}) is one of the best ways to ensure that the code isn't executed until all the elements are loaded into the DOM. It's a jQuery feature.

b. ("form#new_revision").on("keypress", typeCatch); should be $("form#new_revision").on("keypress", typeCatch);. You're missing the $ at the beginning.

Upvotes: 2

Related Questions