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;
}
});
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
idto 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:
Into this instance
this.modelis 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:
I think this naming is more intuitive.
close variables scopes
This code can only works if
myModelis in an scope bigger that it should be:I rather prefer using more encapsulated scopes, even if
myModelhas been declared in the out-side context of your View the View should use a variable of its private context. For exampleCheck the detail that I have also added
varin front ofMyViewbecause if notMyViewwill be awindowglobal variable.use the Backbone urlRoot
In your example, this …
… can be summarized as this: