簡體   English   中英

骨干MVC視圖不會在同步時更新

[英]Backbone MVC view doesn't update on sync

我一直在嘗試學習骨干網。

我設置了模型集合,每個模型都有其自己的視圖,每次模型與服務器同步時都應呈現該視圖。 服務器發回該模型的ID。 似乎設置模型ID 之前正在渲染 如果您查看console.log()的輸出,我將在呈現之前打印出模型的ID。 我還讓它在發生每個事件時將其打印出來。 我得到:

undefined (model id)
add
change:id
change (not sure what changes here?)
sync

另外,我在暫停2秒鍾后更改了模型的名稱屬性model.save('name', 'New Name') 這會導致另一個同步事件, 但是視圖不會更新

這是工作代碼: http : //jsfiddle.net/flackend/brB7y/1/

或在這里查看:

var game_library;

(function($) {

    _.templateSettings = {
        interpolate: /\{(.+?)\}/g
    };    

    var GameModel = Backbone.Model.extend({
        url: '/gh/gist/response.json/2895708/',
        name: undefined,
        initialize: function() {

            // Create a view for this model
            this.view = new GameView({model: this});

            // Sync model with server
            this.save();

            // Bind events
            this.on('sync', this.view.render());
            this.on('all', this.console);
        },
        console: function(event, model, changes) {

            console.log('['+ ++this.i +']-------------(event[:attr], model, changes)----------------');
            console.log(event);
            console.log(model);
            console.log(changes);
        },
        i: 0
    });

    var GameCollection = Backbone.Collection.extend({
        model: GameModel
    });

    var GameView = Backbone.View.extend({
        el: $('#holder'),
        template: $('#game-template').html(),
        render: function() {

            var template = _.template(this.template);
            console.log(this.model.id);
            this.$el.html(template(this.model.toJSON()));
        }
    });

    // Instantiate new game collection
    game_library = new GameCollection;

    // Add a game
    // Note: can only pass in 1 ID from gist, so only add 1 game.
    var games = [
        new GameModel({name: 'Skyrim'})
    ];

    // Note: `game_library.add(new GameModel({name: 'Skyrim'}));` does
    // not work for some reason having to do with instances...
    game_library.add(games);

    // 2 sec later...
    window.setTimeout(function() {

        game_library.get(1).save('name', 'The Elder Scrolls V: Skyrim');
    }, 2000);
})( jQuery );

感謝您的幫助!!

拆下支架

// Bind events
this.on('sync', this.view.render/*()*/);
this.on('all', this.console);

更新了要點, 網址http://jsfiddle.net/brB7y/2/ 我已將您的刷新調用移至可以正常工作的本地函數。 我不確定這背后的技術原因,但這是我以前使用它的方式。

暫無
暫無

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

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