0

I have an editor where users can edit and paste text, and the changes are automatically saved in the server, via AJAX.

Through JS I monitor the state of the textarea, like this:

$("#editor-area").bind "input propertychange", ->
    content = $("#editor-area").val()
    updateRequest = $.ajax(
      url: url
      data: 
        texto:
          contenido: content
      type: "PUT"
    )

Which I extracted from here, answer by Emma Li.

The moment I write a single character, the console shows the same information when one call is performed and processed, but many times. They are so many that my console is overrun and starts overwriting past calls, doing the exactly same thing: updating the record with the new text.

The update method in the controllers looks like

def update
  respond_to do |format|
    if @text.update(text_params)
      format.html {
        redirect_to user_text_path(current_user, @text)
      }
      format.json { render :json => @texto }
    else
      format.html { redirect_to edit_user_path(@user, @text) }
    end
  end
end

There also a before_filter for that option

def set_text_and_user
  @text = get_stuff_from_Db
  @user = @text.user
end

I've been trying to debug this thing, but it has defeated me so far. Have any idea what could be causing this?

Community
  • 1
  • 1
Sebastialonso
  • 1,437
  • 18
  • 34

1 Answers1

0

I actually think, the accepted answer is better.

I've never used the propertychange event, and quick googling shows that - this might not be 100% correct - it's actually an IE-specific event. I'm not sure how (and if) it is supported by other browsers. I do think that you only really need to listen for keyup event on textarea.

Anyway, to the point of your question. There are different ways you can go. They all come down to using a timer. You most likely don't want to send every single keypress to your backend as several concurrent users will simply kill it.

Most common approach is probably throttling. In its simplest, it's a function that catches your events checks the time difference since the previous event and calls the handler only if enough time has passed. You can google for the particulars, I'm pretty sure there are jQuery plugins for that.

bassneck
  • 4,053
  • 4
  • 24
  • 32