the_
the_

Reputation: 1173

Get Model From URL Issue

I have a backbone js app that has a router that looks like:

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

My model looks like:

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

In the JS Console in Chrome, it's showing that there is a GET request to just the /stores url, when it should be making a request to /stores/ID_HERE.

Upvotes: 0

Views: 62

Answers (2)

Alex P
Alex P

Reputation: 6072

Backbone uses a model's id field to determine if it's new or not, and you're passing that in when you construct it.

You could jump through some hoops to do lazy-loading of models on edit - that is, only fetch when trying to edit - but it's probably easier to change your urlRoot property to a simple "/stores/". Backbone will use that urlRoot property, along with the model's ID, to construct the URL. This makes sense; if you have a Store model with an id of 3, you'll want to hit up "/stores/3" to load it regardless of its 'new' status.

If you suspect it's possible for your app to construct a Store without an ID, you might like to override your Store's url function to throw an exception if it's called on a model without an ID.

Upvotes: 1

rcarvalho
rcarvalho

Reputation: 790

Yes and it makes sense, Model.IsNew() is used to check if the model has an id attribute ( see more here, http://backbonejs.org/#Model-isNew ). This way backbone knows when perform save or put to server.

To get data from server using an ID, you'll need something like:

var store = new Store({id: id}); // Ok here we're setting an id on our model.

var Store = Backbone.Model.extend({
    urlRoot: function(){
       return "/stores/"
    }

    GetData : function (){
        this.fetch()
    }  

});

If your model has any attribute, when you perform fetch, all the attributes will be sent to server.

So your url must be the same, but if your model has an Id attribute the url will be something like 'stores/1'. If not will be only 'stores/'

In you API you need to have two methods, one that expect a (int)parameter, and another that expect for nothing.

Hope it helps.

Upvotes: 0

Related Questions