maxko87
maxko87

Reputation: 2940

How to incorporate ajax into coffescript/backbone.js script?

I have a snippet of ajax that will load some data asynchronously:

$(document).ready ->
  $.ajax '/splunk/@orderId',
  type: 'GET'
  success: html ->
    $('#splunk_results').append html

I'm putting it into a coffeescript/backbone.js file:

define dependencies, (template, ...) ->
  OrderDetailsView = Backbone.View.extend
    className: 'expanded_order'

    initialize: ->
      @orderId = @model.get('order_number')
      ...

I'm not really familiar with the structure of a coffeescript/backbone file, so I'm not sure where to put the ajax. Since it references the @orderId, I feel like it should go inside of the class, but it makes some really ugly javascript (and, it seems like it's not working either way right now).

EDIT: Notice that I'm using the @orderId variable in the link, so I think that this call would need to be inside the OrderDetailsView somehow (otherwise it has no way of knowing what @orderId is, right?). Also, I want to be able to return an arbitrary chunk of HTML -- no need for using structured models.

Upvotes: 0

Views: 277

Answers (2)

maxko87
maxko87

Reputation: 2940

In my situation, since I didn't need specific structure to the request, the AJAX call could just be placed at the top of the file (it doesn't interfere with the backbone code at all).

Upvotes: 0

Rimian
Rimian

Reputation: 38418

You shouldn't really need to make that ajax call directly. Create a collection and use fetch. Backbone is good at abstracting ajax calls out for you.

Something like:

SplunkCollection = Backbone.Collection.extend 
  url: 'splunk/'

splunkcollection = new SplunkCollection
splunkcollection.fetch()
...

or maybe just set the URL of your model and fetch it:

@model.url = '/something' //set this somewhere in your model class
@model.fetch()

http://documentcloud.github.com/backbone/#Model-fetch
http://documentcloud.github.com/backbone/#Collection-fetch

Upvotes: 1

Related Questions