骨干从外部json填充集合

Ank*_*nks 5 javascript json backbone.js

下面是我手工构建的集合的现有代码结构.我在我的服务器上有一个json文件,我现在正在尝试加载它,基本上删除手册并根据该数据构建一个集合.想知道我可能需要在下面更改我的代码来帮助解决这个问题.

        var Game = Backbone.Model.extend({
            defaults: {
                name: 'John Doe',
                age: 30,
                occupation: 'worker'
            }
        });


        var GameCollection = Backbone.Collection.extend({
            model: Game,
            url: 'path/to/json',

            parse: function(response) {
                return response;
            }
        });

        var GamesView = Backbone.View.extend({
            tagName: 'ul',

            render: function() {
                //filter through all items in a collection
                this.collection.each(function(game){
                    var gameView = new GameView({model: game});
                    this.$el.append(gameView.render().el);
                }, this)

                return this;
            }
        });

        var GameView = Backbone.View.extend({
            tagName: 'li',

            template: _.template($('#gameTemplate').html()),

            render: function() {
                this.$el.html(this.template(this.model.toJSON()));
                return this;
            }
        });

        var gameCollection = new GameCollection([
            {
                name: 'John Doe',
                age: 30,
                occupation: 'worker'
            }, 
            {
                name: 'John Doe',
                age: 30,
                occupation: 'worker'
            }, 
            {
                name: 'John Doe',
                age: 30,
                occupation: 'worker'
            }
        ]);

        var gamesView = new GamesView({collection: gameCollection});

        $(document.body).append(gamesView.render().el);
Run Code Online (Sandbox Code Playgroud)

Rus*_*oms 10

这是关于Backbone的众多事情之一.我不知道你的后端使用了什么,但是你声明你的服务器上有一个json文件,希望你的json文件中充满了应该在你的集合中的模型.现在这里是魔法代码(鼓号请...):

var GameCollection = Backbone.Collection.extend({
  model: Game,
  url: 'path/to/json/on/external/server',
});

var gameCollection = new GameCollection();
gameCollection.fetch();
Run Code Online (Sandbox Code Playgroud)

不是很多,对吗?当然,您可以添加或更改一些选项fetch,因此请查看以下文档:http://backbonejs.org/#Collection-fetch.Backbone使用jQuery.ajax()默认值,因此请查看此处的文档以查看所有选项:http://api.jquery.com/jQuery.ajax/

除非服务器上的模型与主干模型不匹配,否则不应在集合中使用自定义分析.

要了解的事情: fetch是异步的.与服务器通信需要时间,其余的javascript将继续并完成.您可能需要至少为该success选项添加一个回调函数,该函数将在fetch完成时调用,并且在出现问题时也可以添加一些内容error.您可以将数据添加为查询字符串,以便后端可以使用该data选项使用它,数据必须是对象.这是一个例子:

gameCollection.fetch({
  data: {collection_id: 25},
  success: function(){
    renderCollection(); // some callback to do stuff with the collection you made
  },
  error: function(){
    alert("Oh noes! Something went wrong!")
  }
});
Run Code Online (Sandbox Code Playgroud)

fetch 应该以JSON格式接收数据,因此您的url应该独占返回JSON,或者设置为检测AJAX请求并使用JSON响应它.