1

I need to find a way to attach a jQuery autocomplete handler on to an input field that is rendered as part of an eco template.

Here's what works fine when the input field is on the page in the markup

HTML:

<input type="text" name="thing[name]" value="" id="the_input_field">
<input type="hidden" name="thing[id]" value="" id="the_id_field">

Coffee:

$("#the_input_field").autocomplete
  source: "/path_to/suggest"
  select: ( event, ui ) ->
    $( "#the_id_field" ).val ui.item.id

I have tried a version that used a setTimeout to apply the autocomplete 3 seconds later which worked but I know this is NOT the solution, just tracking down the issue. What I need is a callback to pass into render so it can attach the autocomplete when it's done.

Hope someone can shed some light on this.

Cheers

slarti42uk
  • 451
  • 3
  • 9

1 Answers1

1

Ok so I struggled for a while but a simple solution now seems to be to add the calls into the Spine controller after the render method. Why I didn't see this I dont know.

So what I have in the Spine controller now is:

class WorkRequests extends Spine.Controller

constructor: ->
  super
  @render()

  render: =>
    @html @view('workrequests/new')
    @renderUi()

  renderUi: =>
    $("#the_input_field").autocomplete
      source: "/path_to/suggest"
      select: ( event, ui ) ->
        $( "#the_id_field" ).val ui.item.id 

window.WorkRequests = WorkRequests

So far this seems to work and add the jQuery stuff after the view has been rendered. I'm yet to see if there is any issue with a very heavy rendered page and the timing but I think this is a solution.

(kicks self in the head)

slarti42uk
  • 451
  • 3
  • 9
  • Why are you splitting out the renderUi method? Seems to me it should all just be in the render method. Because it's logic that has to happen each time that template is rendered. – SpoBo Mar 08 '12 at 12:34
  • The only reason was that I was moving toward a Spine stack and there is a render function in both the New and Edit controllers. As these are slightly different I was trying to keep it DRY and have it in a common place. The 'New' and 'Edit' controllers in the stack extend WorkRequests. – slarti42uk Mar 08 '12 at 23:35