tenaz3.comp
tenaz3.comp

Reputation: 512

How to make third-party request in backbone

I need to use backbone in this part without use the server, just in client side. Need: When user click on button then has to make a request in third-party(different domain). I have to grab the answer and show to user. The problem is how i pass my grab data to view OBS: I don`t have this model in rails, it's just fake (pretend) I already tried:

class App.Routers.Datas extends Backbone.Router
 routes:
 '': 'show'
 initialize: ->
   @collection = new App.Collections.Data()
   @collection.fetch({reset: true})

 show: ->
   view = new App.Views.DatasShow(collection: @collection)
   $('#container').html(view.render().el)

Where im trying fetch data

class App.Collections.Datas extends Backbone.Collection

 model: App.Models.Data

 fetch: -> # override method
 $.ajax '/url', #third-party request
  dataType: 'jsonp',
  success: (res, status, xhr) -> # the problem is here, how to pass data to a collection?
    @collection = res.data
    return @collection
  error: (xhr, status, err) ->

View

class App.Views.DatasShow extends Backbone.View

template: JST['datas/show']
render: ->
  $(@el).html(@template(fetched: @collection))
  this

show.jst.eco

<%= @fetched.length %>

Upvotes: 0

Views: 150

Answers (1)

Ahmed ElBayaa
Ahmed ElBayaa

Reputation: 266

You needn't to override the fetch method; you just need to define your url and you also need to override the parse method which is automatically called after fetching to parse the returned response and assign it to the collection http://backbonejs.org/#Collection-parse

class App.Collections.Datas extends Backbone.Collection

  model: App.Models.Data

  initialize: ->
    @url = 'Enter URL here' # The fetch method will use this url by default

  parse:(response, options)->
    super(response.data, options)

PS

the word data is the plural of datum

Upvotes: 1

Related Questions