the_
the_

Reputation: 1173

Undefined id fetch

My backbonejs app has a model that looks like:

var Store = Backbone.Model.extend({
   urlRoot: "/stores/" + this.id
});

and I have a router that looks like:

var StoreRouter = Backbone.Router.extend({
   routes: {
      'stores/edit/:id': 'edit'
   },
   edit: function(id){
      var editStoresView = new EditStoresView({
         el: ".wrapper",
         model: new Store({ id: id })
      });
   }
});
var storeRouter = new StoreRouter();
Backbone.history.start({ pushState: true, hashChange: false });

but then in my view I have:

var EditStoresView = Backbone.View.extend({
   ...
   render: function() {
       this.model.fetch();
       this.$el.append ( JST['tmpl/' + "edit"]( this.model.toJSON() ) );
   }

Unfortunately, this gives a call to localhost/stores/undefined, but I'm not sure why?

Upvotes: 0

Views: 120

Answers (1)

Sai Dubbaka
Sai Dubbaka

Reputation: 631

The reason why you're getting "localhost/stores/undefined" call is because you have below code.

urlRoot: "/stores/" + this.id

When you use model.fetch() it uses urlRoot plus ID of the model to fetch the data. In other words, you should have urlRoot as something like "/stores/" only and should not directly apply any ID.

One more thing, you should write below code in "sucess" callback of the fetch() method because the model data won't be available as soon as you call fetch() (since it's a sync request to the server).

this.model.fetch();    
this.$el.append ( JST['tmpl/' + "edit"]( this.model.toJSON() ) );

Change that to

   var el = this.$el;
   this.model.fetch({ success : function(model, response, options) {
       el.append ( JST['tmpl/' + "edit"]( model.toJSON() ) );
   });

Hope that helps! Happy coding!

Upvotes: 2

Related Questions