开发者

Backbone.js why a model from a collection doesn't have url set?

I am still relatively new to Backbone. I'm just beginning to get a sense of how it works. I 've been using Rails for a whi开发者_如何学Gole and it's what is giving me some hint at times of using Backbone. so here goes:

Simple, I have a Company model over in Rails say I do in javascript console

companies = new Backbone.Collection();
companies.url = '/companies';
companies.url;        // '/companies'
companies.fetch();
company = companies.at(0);
company.url

The last line, "company.url" doens't return what I expect, what I expect is something like '/companies/12345' so that when I update company and decide to save it, it will know where to "put" to.

So does that mean that everytime I want something saved, I have to save on the whole collection?(!)


I would take a look at what company.url() is returning. Saving the whole collection should not be necessary.


I was trying your problem, and found that the models are not getting an id to it. So the url method on the models is not working. So i think you need to put your collections like below (what i tried)

        cltn = Backbone.Collection.extend({             
            model:modelName,
            parse:function(res){
                var i = 0;
                var itms = _.map(res.items, function(o){                        
                    o.id = ++i;
                    return o
                })                  
                return itms;
            }
        });
        cltnInst = new cltn();
        cltnInst.url="/combodata.json?";
        cltnInst.fetch();

Then in your firebug type the below codes.

cltnInst.url; // this is a string props. output will be "/combodata.json?"
cltnInst.at(0).url() // this is a method props output will be "/combodata.json?/1"

combodata.json will be of this format

{
"identifier": "title",
"items": [
    {
        "title": "A",
        "tag": "htmlcss",
        "date": "today"
    }, ...
]}

Please correct me if my answer is wrong.


I have actually made a mistake in the step where I make an attempt to create a new companies collection. So instead of

var Companies = new Backbone.Collection()

I should really do something like this:

var Companies = Backbone.Collection.extend({
  model: Company,
  url : '/companies'
});

var Company = Backbone.Model.extend();

var companies_collection = new Companies()

companies_collection.fetch() 
companies_collection.models[0].url() // '/projects/123'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜