2012-09-01 39 views
2

我对Backbone.js非常新,并且一直在遵循一些教程来提供下面的脚本。我试图实现的是使用我的路由时从休息API检索JSON数据。如果您查看朋友路线的人员功能,您可以看到即将与此相关的信息。我哪里错了?Backbone.js + REST

<!DOCTYPE html> 
<html> 
<head> 
    <title>I have a back bone</title> 
</head> 
<body> 
    <button id="add-friend">Add Friend</button> 
    <ul id="friends-list"> 
    </ul> 
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> 
    <script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js"></script> 
    <script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js"></script> 
<script> 
Friend = Backbone.Model.extend({ 
    name: null, 
    age: null, 
}); 
FriendDetailModel = Backbone.Model.extend(); 
FriendDetailCollection = Backbone.Collection.extend({ 
    url: 'slim/index.php/friends/', 
    model: FriendDetailModel 

}); 

Friends = Backbone.Collection.extend({ 
    initialize: function(models, options) { 
     this.bind("add",options.view.addFriendLi); 
    } 
}); 
AppView = Backbone.View.extend({ 
    el: $("body"), 
    initialize: function() { 
     this.friends= new Friends(null, {view:this}); 
    }, 
    events: { 
     "click #add-friend": "showPrompt", 
    }, 
    showPrompt: function() { 
     var friend_name = prompt("Who is your friend?"); 
     var friend_age = prompt("What is your friends age?"); 
     var friend_model = new Friend({name: friend_name, age: friend_age}); 

     this.friends.add(friend_model); 
    }, 
    addFriendLi: function(model) { 
     $("#friends-list").append("<li>" + model.get('name') + " " + model.get('age') + "</li>"); 
    } 
}); 
var appview = new AppView; 

AppRouter = Backbone.Router.extend({ 
    routes: { 
     "friends":"people", 
     "person/:name":"personDetail" 
    }, 

    people: function() { 
     console.log('all the people'); 
     var people = new FriendDetailCollection; 
      people.fetch({ 
        success: function(data) { 
          console.log(data); 
        } 

    }, 

    personDetail: function(name) { 
     console.log('one person named ' + name); 
    } 
}); 

var approuter = new AppRouter; 
Backbone.history.start(); 
</script> 
</body> 
</html> 

运行people.fetch CONSOLE.LOG后显示

d 
_byCid: Object 
_byId: Object 
length: 4 
models: Array[4] 
__proto__: x 

如果我的console.log(data.toJSON());它返回

[] 
+1

你能否让你的问题更具体些?究竟出了什么问题? (例如错误,没有数据等) – jmk2142

+0

我增加了一些信息。感谢您的帮助! –

回答

3

我结束了做解决问题如下:

我创建的路由器之外的新的集合:

var people = new FriendDetailCollection; 

当我创造我指定的集合视图我以前创建。

friendview = new FriendView({collection: people}); 

我在FriendView中有一个错字。以前我有_.bind(这个'render')。它需要是

_.bindAll(this,'render'); 

此外,我把我的console.log在我的FriendView中的render()函数。

FriendView = Backbone.View.extend({ 
     el: $("body"), 
     initialize: function() { 
       _.bindAll(this,'render'); 
       this.collection.bind('reset', this.render); 
     }, 
     render: function() { 
       console.log(this.collection.toJSON()); 
     } 

});