骨干模型在id属性中有url

时间:2012-06-15 15:47:43

标签: backbone.js

我不确定这是否应该如此,但在调试我的主干应用程序时,我意识到我的模型在其ID属性中具有API的URL,例如:

    App.houseCollection.models[0]
       Object
        _callbacks: Object
        _escapedAttributes: Object
        _pending: Object
        _previousAttributes: Object
        _silent: Object
        attributes: Object
        changed: Object
        cid: "c4"
        collection: Object
        id: "/api/v1/post/4/"
        __proto__: Object

我有一条路线需要通过ID访问集合中的模型,即只有数字ID,在本例中为id = 4

执行App.houseCollection.get('/api/v1/post/4/')有效,但我希望能够App.houseCollection.get(4)

1 个答案:

答案 0 :(得分:2)

据推测,您的服务器将id作为URL返回,而不仅仅是一个数字。修复服务器或向模型添加parse method以清理id

parse: function(response) {
    var matches;
    if(response.id
    && (matches = response.id.match(/\/(\d+)\/$/)))
        response.id = parseInt(matches[1], 10);
    return response;
}

你可能想要调整正则表达式。

相关问题