Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone fetch() always returns same model

For some reason, my code is always returning the same model even though I can see that the correct id is being passed in after I select the item in a listView page.

// main.js (relavent function)

    venueDetails: function (id) {
        // here, id is correct
        var venue = new Venue({_id: id});
        venue.fetch({success: function(){
            // here, the id of venue is changed for some reason
            console.log(venue.id);
            $("#content").html(new VenueView({model: venue}).el);
        }});
        this.headerView.selectMenuItem();
    },

The model,

// model.js (relavent model)

    var base = 'http://localhost:3000';

    window.Venue = Backbone.Model.extend({
        urlRoot: base+"/venues",
        idAttribute: "_id",
    });

    window.VenueCollection = Backbone.Collection.extend({
        model: Venue,
        url: base+"/venues?populate=true"
    });

In the picture, you can see where the model.id is different from whats in the url enter image description here

EDIT: added router mapping

var AppRouter = Backbone.Router.extend({

routes: {
    ""                     : "home",
    <!-- venues -->
    "venues"               : "venueList",
    "venues/page/:page"    : "venueList",
    "venues/add"           : "addVenue",
    "venues/:id"           : "venueDetails",
like image 607
remotevision Avatar asked Feb 05 '26 20:02

remotevision


2 Answers

I don't know if the _id attribute is being accessed correctly in the model, since venue.fetch seems to be making a call out to some type of default.

Maybe try:

   window.Venue = Backbone.Model.extend({
        urlRoot: base+"/venues",
        idAttribute: this.options._id,
    });

(and pull the id from the options hash)

And if that doesn't work, try declaring the idAttribute dynamically:

   window.Venue = Backbone.Model.extend({
        urlRoot: base+"/venues",
        idAttribute: function() { return this.options._id },
    });
like image 51
CamelBlues Avatar answered Feb 08 '26 21:02

CamelBlues


This

 var base = 'http://localhost:3000';

is a bad idea, and completely unnecessary. Just get rid of that entirely. Just use absolute paths (like '/venues') as URLs and your app will work properly no matter where it's running.

Between your code and screenshot there are 2 different ports. Are you sure you are talking to the right application server?

Otherwise, have you checked your server side code for a bug? It could be something as simple as the server side code is using the wrong value when querying the database.

like image 22
Peter Lyons Avatar answered Feb 08 '26 20:02

Peter Lyons



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!