2012-09-01 75 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()); 
     } 

});