0

所以我设法弄清楚如何从外部文件填充我的集合,并根据 url 呈现视图,但我遇到了问题。下面的代码按预期工作,除了页面加载,我收到以下错误:

Uncaught TypeError: Cannot call method 'get' of undefined 

摆脱“view.render()”消除了错误,但现在应用程序不再响应 url 中的 ID 更改(例如,从 #/donuts/1 到 #/donuts/2 不会更新视图)

有人可以在这里指出我正确的方向吗?

编码:

(function(){
var Donut = Backbone.Model.extend({
    defaults: {
        name: null,
        sprinkles: null,
        cream_filled: null
    }
});
var Donuts = Backbone.Collection.extend({
    url: 'json.json',
    model: Donut,
    initialize: function() {
        this.fetch();
    }
})

var donuts = new Donuts();

var donutView = Backbone.View.extend({
     initialize: function() {
        this.collection.bind("reset", this.render, this)
    }, 
    render: function() {
        console.log(this.collection.models[this.id].get('name'))
    }
});

var App = Backbone.Router.extend({
    routes: {
        "donut/:id" : 'donutName',
    },

    donutName: function(id) {
        var view = new donutView({
            collection: donuts,
            id: id
        });
        view.render();

    }
});

var app = new App();
Backbone.history.start();
})(jQuery);

JSON:

[
    {
        "name": "Boston Cream",
        "sprinkles" : "false",
        "cream_filled": "true"
    },
    {
        "name": "Plain",
        "sprinkles": "false",
        "cream_filled": "false"
    },
    {
        "name": "Sprinkles",
        "sprinkles": "true",
        "cream_filled": "false"
    }
]
4

1 回答 1

1

这里看起来有点流程问题。您可以让视图监听集合的“重置”事件。因此,当重置时,视图将呈现。那很好。但我相信问题出在你的路由器上。路由时,您正在创建视图的新实例,但不对集合做任何事情,因此它的状态是相同的。

由于您已经在观察集合,因此不要对视图执行任何操作。路由时,更新集合的 url,然后进行获取。这将触发重置,然后视图应自行更新。

于 2012-06-11T21:27:42.123 回答