Khalid Dabjan
Khalid Dabjan

Reputation: 2797

passing the url property to model not working

I have a simple inheritance hierarchy of Backbone views, and want all of my views to have one generic model. Only the url property of the model in these views will differ. so I pass the url when initializing the model.

The parent generic view is:

GenericView = Backbone.View.extend({
template: "friendsList-template.html",
initialize: function(){
    var that = this;
    that.model.fetch({
        success: function(model,response){
            that.handleResponse(response);
        },
        error: function(){
            //handle error
        }
    });
}
});

And the child view is:

PersonView = GenericView.extend({
el:$("#container"),

personData: {},
template: "profile-template.html",
model = new GenericModel({
    url:"testRouter.php"
});//here is where I'm defining the url
initialize: function(){
    PersonView.__super__.initialize.apply(this);
},
render: function(){
    var that = this;
    $.get(this.templatesPath + this.template, function(resTemplate){
        var html = Mustache.render(resTemplate, that.personData);
        that.$el.html(html);
    });
},
handleResponse: function(res){
    this.personData = res;
    this.render();
}
});

And the GenericModel is simply empty model (for now at least)

GenericModel = Backbone.Model.extend({
});

In console, I'm getting the following error:

Uncaught Error: A "url" property or function must be specified backbone.js:1559

Is my hierarchy is the problem or something else? Any thoughts?

Upvotes: 1

Views: 357

Answers (1)

mu is too short
mu is too short

Reputation: 434665

From the fine manual:

constructor / initialize new Model([attributes], [options])
[...]
{url: "..."} and/or {urlRoot: "..."} options may be passed when creating a new model that needs to have a custom one-off URL endpoint.

Note two things:

  1. The first argument to the constructor is the attributes object.
  2. The url goes in the second options object.

So you should be doing this:

var model = new GenericModel(null, {
    url: "testRouter.php"
});

if you want to set the url when you create the model.

Demo: http://jsfiddle.net/ambiguous/gSYug/

Upvotes: 1

Related Questions