how to get data from server in backbone
-
13-12-2019 - |
Question
I am creating an app in backbone. This current code works but now I want to get the data from the server. My method at /myfriends/getData returns a json of friends name and etc. How can I make this code to get that json from the server. I read up a little and they are using routes etc…I just need to use it on one page of my app so I do not want to do a lot of routing etc
thanks
$(function() {
FriendList = Backbone.Collection.extend({
initialize: function(){
this.bind("add", function( model ){
alert("hey");
view.render( model );
})
}
});
FriendView = Backbone.View.extend({
tagName: 'li',
events: {
'click #add-input': 'getFriend',
},
initialize: function() {
this.friendslist = new FriendList;
_.bindAll(this, 'render');
},
getFriend: function() {
var friend_name = $('#input').val();
this.friendslist.add( {name: friend_name} );
},
render: function( model ) {
$("#friends-list").append("<li>"+ model.get("name")+"</li>");
console.log('rendered')
},
});
var view = new FriendView({el: 'body'});
});
here is a working copy
http://jsfiddle.net/thomas/Yqk5A/
thanks
TIRED
this is what I have to show the data and tried after the suggestion and still no luck
$(function() {
FriendList = Backbone.Collection.extend({
initialize: function(){
this.bind("add", function( model ){
alert("hey");
view.render( model );
})
}
});
FriendsServer = new Backbone.Collection({
initialize: function(){
url : '/friends/Data',
this.bind("test", function( model ){
view.render( model );
})
}
});
FriendView = Backbone.View.extend({
tagName: 'li',
events: {
'click #add-input': 'getFriend',
},
initialize: function() {
this.friendslist = new FriendList;
_.bindAll(this, 'render');
},
getFriend: function() {
var friend_name = $('#input').val();
this.friendslist.add( {name: friend_name} );
},
render: function( model ) {
$("#friends-list").append("<li>"+ model.get("name")+"</li>");
console.log('rendered')
},
});
FriendsServerView = Backbone.View.extend({
tagName: 'div',
render: function( model ){
$("#jsonData").html(FriendServer.fetch);
}
});
var view = new FriendView({el: 'body'});
var view = new FriendsServerView({el: 'body'});
});
in my html I have a div to populate with json data
Solution
You just set the url property of your collection and call .fetch() on your collection to load the data from your server. More info at:
http://backbonejs.org/#Collection-fetch
Also, I would bind your model/collection events to your view, not to the model/collection.