fluent
fluent

Reputation: 2403

Fetching items with Backbone seems to ignore the id passed in

I have these routes in my webservice and I can hit either of them directly through the browser and I return the correct value.

app.get('/repairs', repair.findAll);
app.get('/repairs/:id', repair.findById);

When I ask Backbone to do this I am unexpectedly getting a call to

app.get('/repairs', repair.findAll);

when I expect it to reach

app.get('/repairs/:id', repair.findById);

The piece of code that appears to be calling "/repairs" rather than "/repairs/:id" is

var EditRepair = Backbone.View.extend({
        el : '.page',
        render : function(options) {
            var scope = this;
            var repair = new Repair({id: options.id});                    

            //This has the correct id
            console.log(options.id);

            //I would expect this to call /repairs/12344312
            //However it calls /repairs
            repair.fetch({
                success : function(repair){
                    var template = _.template($('#edit-repair-template').html(), {repair : repair});
                    scope.$el.html(template); 
                }
            });
        }
    }); 

    var Repair = Backbone.Model.extend({
        urlRoot : 'repairs'
    }); 

    var Router = Backbone.Router.extend({
        routes: {
            'edit/:id' : 'editRepair'
        }    
    });

    var editRepair = new EditRepair();    
    var router = new Router();

    router.on('route:editRepair', function(id) {
        console.log('Edit Id : ' + id);
        editRepair.render({id:id});
    });

The options.id can be console.logged and shows the correct id of the item. I've had a few issues so far with the difference between _id in mongodb and id in backbone which I have worked around but for the life of me I cannot see why this is issuing a call to repairs and not repairs/id.

Any help appreciated.

Upvotes: 1

Views: 148

Answers (1)

fluent
fluent

Reputation: 2403

My fault, I had an ajax prefilter that was encoding the uri components.

This was messing up the requests being issued.

    $.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
      options.url = "http://localhost:3000/" + encodeURIComponent( options.url );
      console.log(options.url);
    });

Changed to

        $.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
          options.url = "http://localhost:3000/" + options.url;
          console.log(options.url);
        });

Upvotes: 2

Related Questions