0

Based on a lot of resources found on the internet, i'm trying to create my custom model action which sends a POST /api/v1/users/subscribe request. My code looks like this:

@UserModel = Backbone.Model.extend
  urlRoot: '/api/v1/users'

  subscribe: (opts) ->
    url = "#{@urlRoot}/subscribe"
    options =
      url:    @url
      method: 'POST'
    _.extend @options, opts

    return (@sync or Backbone.sync).call this, null, this, @options

However, when using it as follows:

user = new UserModel
user.subscribe()

It make s a GET /api/v1/users request. Can you please explain me what is wrong with my code? Almost all examples about custom methods looks like this: https://gist.github.com/sap1ens/4692429 and my code is an exact port of it.

Thanks in advance

mbajur
  • 4,406
  • 5
  • 49
  • 79
  • Just a code check. Are you sure you want to `_.extend @options, opts` in that order? Generally the default options (in your case `opt`) are meant to be overriden. So you'd want to do `opts = opts || {}` `_.extend opts, @options`. – seebiscuit Feb 08 '15 at 13:23
  • it turned out to be a coffe --> js compilation issue because using a js file with provided gist code works great. However, i still have no idea why it's not working in coffee. – mbajur Feb 08 '15 at 17:13

2 Answers2

2

from backbonejs.org: options – success and error callbacks, and all other jQuery request options

The options parameter of the Backbone.sync method, accepts jquery request options. To specify the type of request, the proper jquery option is 'type' (jQuery.ajax). The following code works

var UserModel = Backbone.Model.extend({
    urlRoot: '/api/v1/users',
    subscribe: function (opts) {
        var url = "this.urlRoot/subscribe"
        var options = {
            url:    url,
            type: 'POST'
        };
        _.extend( options, opts);

        return Backbone.sync.call( this, null, this, options);
    }
});

user = new UserModel();
user.subscribe();

P.S.: I am not good at coffee script, so roughly translated it to plain js.

Kumaran
  • 41
  • 4
  • ok, it seems that it's some kind of a glitch caused by coffee -> js decoding cause your code works just fine while mine, even with `method` changed to `type`, fires a **GET** request to completely wrong url. I can't accept your answear cause it's not a direct solution to my problem but big thanks for pointing that issue out! Upvoting :) – mbajur Feb 07 '15 at 19:50
1

Be careful with the @s in url: @url, _.extend @options, opts and your return statement. Remember Coffescript will compile @ into this.

@UserModel = Backbone.Model.extend
  urlRoot: '/api/v1/users'

  subscribe: (opts) ->
    url = "#{@urlRoot}/subscribe"
    options =
      url: url
      type: 'POST'
    _.extend options, opts

    return (@sync or Backbone.sync).call @, null, @, options
Josue Montano
  • 521
  • 4
  • 16