underscore666
underscore666

Reputation: 1739

Fetch data having a specific id defined in the view instance

I need to fetch data having a specific id
and which id is defined in the view instance.
Here the example, see the comments in MyModel definition:

// my view instance
var myView = new MyView({
    model: {id: 12321}
});

MyView = Backbone.View.extends({
        initialize: function()
        { 
            myModel.fetch();
        }
});

MyModel = Backbone.Model.extends({
        url: function url ()  
        {
          // how to get the id passed to view instance?
          return "http:..../id/" + this.id; 
        }
});

Upvotes: 0

Views: 59

Answers (1)

fguillen
fguillen

Reputation: 38832

Model should not has any knowledge of the existence of the View, so the View should be the one that sais to the Model which id to fetch:

MyView = Backbone.View.extends({
        initialize: function()
        { 
            myModel.id = this.model.id;
            myModel.fetch();
        }
});

(I've used your example code as template for my example, but I have to say I feel several weird things on it, I suppose is just a matter of taste)

Update: My very personal taste opinions

Is very difficult to do this but as you requested I'll share with you my very personal code review of your example code. Take this as it is: a very humble opinion.

this.model confused

I would not use attribute names that can create confussion:

var myView = new MyView({
    model: {id: 12321}
});

Into this instance this.model is making reference to a raw Hash but in a Backbone context this is against the intuitive feeling that this is gonna be a Backbone.Model.

I rather change it for something like this:

var MyView = Backbone.View.extend({
  initialize: function( opts ){
     this.model_id = opts.model_id;
  }
})
var myView = new MyView({ model_id: 12321 });

I think this naming is more intuitive.

close variables scopes

This code can only works if myModel is in an scope bigger that it should be:

MyView = Backbone.View.extends({
        initialize: function()
        { 
            myModel.fetch();
        }
});

I rather prefer using more encapsulated scopes, even if myModel has been declared in the out-side context of your View the View should use a variable of its private context. For example

var MyView = Backbone.View.extends({
  initialize: function( opts ) { 
    this.model = opts.model;
    this.model.fetch();
  }
});

var myView = new MyView({ model: myModel });

Check the detail that I have also added var in front of MyView because if not MyView will be a window global variable.

use the Backbone urlRoot

In your example, this ...

MyModel = Backbone.Model.extends({
    url: function url ()  
    {
      // how to get the id passed to view instance?
      return "http:..../id/" + this.id; 
    }
});

... can be summarized as this:

MyModel = Backbone.Model.extends({
    urlRoot: "http:..../id"
});

Upvotes: 3

Related Questions