So I am finally giving one of these front end frameworks a try and I figured I would go with backbone.js as it has been around for awhile and has proven production value.
I am doing some testing with it on my localhost (XAMPP). I am just grabbing some data in JSON format and adding to to a collection. As this is the first time I'm doing this I am assuming I am doing something wrong but my code looks like this:
index.php:
<html>
<head>
<title>Backbone Testing</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="js/underscore-min.js"></script>
<script src="js/backbone-min.js"></script>
</head>
<body>
<div id="container" style="margin-left: auto; margin-right: auto;"></div><br /><br />
</body>
<script src="mv/app.js"></script>
<script>
var test = new App();
</script>
</html>
app.js:
/*
Model
*/
var App = Backbone.Model.extend({
initialize: function() {
$.ajax({
type: "POST",
url: "getData.php",
success: function(data) {
var jData = JSON.parse(data);
console.log(jData); // Data coming in is in proper format
// After commenting out the lines below
// it doesn't crash
//var users = new Data;
//users.reset(jData);
},
error: function(xhr) {
console.log(xhr);
alert("Error!");
}
});
},
defaults: {
SURNAME: "",
FST_NAME: ""
}
});
/*
Collection
*/
var Data = Backbone.Collection.extend({
model: App,
});
All I am doing is pulling some data from my mock database and attempting to add it to a collection, however when it does get added to the collection via users.reset(jData) I get no JavaScript errors but the webpage just becomes unresponsive and shortly after that my server crashes (XAMPP stops working).
Any help would be appreciated as I have looked at several threads here and various Google searches and can not find out what I am doing wrong. Thanks!
It seems the reason for the crash was a repeating AJAX call. After adjusting the app.js now looks like:
$(function() {
$.ajax({
type: "POST",
url: "getData.php",
success: function(data) {
var jData = JSON.parse(data);
var users = new Data;
users.set(jData);
},
error: function(xhr) {
console.log(xhr);
alert("Error!");
}
});
});
/*
Model
*/
var App = Backbone.Model.extend({
defaults: {
SURNAME: "",
FST_NAME: ""
}
});
/*
Collection
*/
var Data = Backbone.Collection.extend({
model: App,
});
Now I just need to figure out how to render a view and I'll be good, but I suppose that's for another post.