0

我一直试图解决这个问题几个小时,但似乎无法让它发挥作用。在“朋友”集合中加载的 json 文件不会填充到视图中。

var Friend = Backbone.Model.extend({
    defaults: {
        "name": "Unknown",
        "job": "Unknown"
    }
});
var friend = new Friend({

});

var Friends = Backbone.Collection.extend({
    model: Friend,
    url: '/friends.json',
    initialize: function() {
        this.fetch();
    }
});
var friends = new Friends();

var FriendsView = Backbone.View.extend({
    tagName: "ul",
    template: _.template('<li><%= name %> is a  <%= job %></li>'),
    render: function(){
        this.$el.html(this.template(this.model.toJSON()));
    }
});
var friendsView = new FriendsView({ model: friend });

friendsView.render();
$('#here').html(friendsView.el);

JSON 看起来像这样:

{
    "name": "Timmy",
    "job": 'Sky Diver'
},
{
    "name": "Michael",
    "job": 'Hat salesman'
}

我可以在控制台中看到 json 文件是通过 ajax 加载的。提前致谢。

4

1 回答 1

0
var Friend = Backbone.Model.extend({
    defaults: {
        "name": "Unknown",
        "job": "Unknown"
    }
});

var Friends = Backbone.Collection.extend({
    model: Friend,
    //url: '/friends.json',
});

var friends = new Friends([{
    "name": "Timmy",
    "job": 'Sky Diver'
},
{
    "name": "Michael",
    "job": 'Hat salesman'
}]);

var FriendsView = Backbone.View.extend({
    template: _.template('<li><%= name %> is a  <%= job %></li>'),
    render: function(){
        this.collection.each(function(model){
            this.$el.append(this.template(model.toJSON()));
        }, this)
    }
});
var friendsView = new FriendsView({ el: $('#here'), collection: friends });

friendsView.render();

// though for fetching the remote data you'd want..
// friends.fetch({ success: friendsView.render })

http://jsfiddle.net/lector/yrZgH/

于 2013-08-24T03:30:26.133 回答