Created
May 11, 2015 23:06
-
-
Save stacylondon/5642b86b7a5ba2157818 to your computer and use it in GitHub Desktop.
Refactor 5 - Backbone Models, Collections
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ------------------------------------- | |
// hand-written ajax | |
// ------------------------------------- | |
var PageOneView = Backbone.View.extend({ | |
el: '#pageOneMainContainer', | |
initialize: function() { | |
this.getSomeData(); | |
}, | |
getSomeData: function() { | |
var self = this; | |
$.ajax({ | |
type: 'GET', | |
url: 'SomeEndpoint', | |
data: formData, | |
dataType: 'json', | |
success: function(data, textStatus, jqXHR) { | |
self.displayResults(data); | |
}, | |
error: function(jqXHR, textStatus, errorThrown) { | |
self.displayError(); | |
} | |
}); | |
}, | |
displayResults: function(data) { | |
}, | |
displayError: function() { | |
} | |
}); | |
// ------------------------------------- | |
// using Backbone | |
// ------------------------------------- | |
// initialize view | |
var pageOneView = new PageOneView({ | |
collection: new PageOneCollection([]), | |
}); | |
var PageOneView = Backbone.View.extend({ | |
el: '#pageOneMainContainer', | |
template: _.template($('#page-one-template').html()), | |
initialize: function() {}, | |
render: function() { | |
this.$el.html(this.template({'collection': this.collection})); | |
// maintain chainability | |
return this; | |
} | |
}); | |
var PageOneCollection = Backbone.Collection.extend({ | |
initialize: function(models, options) {}, | |
model: PageOneModel, | |
// RESTful web service URL | |
url: '/SomeEndpoint' | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment