簡體   English   中英

Backbone.js-視圖未重新加載

[英]Backbone.js - View not reloading

因此,我設法弄清楚了如何從外部文件填充我的收藏集,並基於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"
    }
]

在這里看起來有點流程問題。 您可以在視圖中偵聽集合的“重置”事件。 因此,當進行重置時,視圖將呈現。 很好 但我相信問題出在您的路由器上。 路由時,您正在創建視圖的新實例,但不對集合進行任何操作,因此其狀態是相同的。

由於您已經在觀察集合,因此對視圖不執行任何操作。 路由時,請更新集合的網址,然后進行提取。 這將觸發重置,然后視圖應自行更新。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM