0

Is there any way to create your own ajax method to make a POST request instead of using save ?

mmontes11
  • 3
  • 3
  • You can, but there is debate as to whether or not this is a good approach. Check http://stackoverflow.com/questions/11331604/backbone-js-ajax-calls for a more detailed discussion. – snozza Jul 22 '15 at 07:09
  • Simple way is to just use `$.ajax` with `type = post` instead of using backbone model. Why would you want to do it in the first place? – AdityaParab Jul 22 '15 at 07:10
  • I already found a solution. Thank you very much. – mmontes11 Jul 22 '15 at 09:02

2 Answers2

0

Save not only fires the AJAX request but triggers events and validation, so I wouldn't write my "own" save method. However, you can always write a model function like:

var SomeModel = Backbone.Model.extend({
    urlRoot: "/some/url",
    altSave: function () {
        $.post(this.urlRoot, {
            /*assemble your post data*/
        }, function (response) {

        });
    }
});

var s = new SomeModel();
s.altSave();

calling s.altSave(); will fire a POST request.

Evgeniy
  • 2,915
  • 3
  • 21
  • 35
Akos K
  • 7,071
  • 3
  • 33
  • 46
0

That's right and it works but I think this is a better solution:

'use strict';

define([
    'underscore',
    'backbone',
    'config/appConfig'
],function(_,Backbone,Config){

    var StatsModel = Backbone.Model.extend({
        urlRoot: Config.urlStats,
        url: function() {
            var url = this.urlRoot + "/resource";
            return url;
        },
        defaults: {
            metricID: '',
            groupByID: ''
        },
        requestStats: function(opts) {
            var url = this.url(),
                options = {
                    url: url,
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(this.attributes)
                };

            _.extend(options, opts);

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

Thank you very much

mmontes11
  • 3
  • 3
  • No, because: 1. it overrides the default `url` of `Backbone.Model`, which is unnecessary, 2. `Backbone.sync`'s underlying implementation may change, 3. you have to dig into Backbone source to know what happens really happens on `return (this.sync || Backbone.sync).call(this, null, this, options);`. You may know it today, but you'll forge it after a few months, imagine what will happen to new developers. My solution is more straightforward and developer friendly and doesn't require you digging into a library's source. Use that if you care to write maintainable code. – Akos K Jul 22 '15 at 13:24