Skip to content

Instantly share code, notes, and snippets.

@Jhony0311
Last active August 29, 2015 14:12
Show Gist options
  • Save Jhony0311/3d44b39e210557b5cd79 to your computer and use it in GitHub Desktop.
Save Jhony0311/3d44b39e210557b5cd79 to your computer and use it in GitHub Desktop.
View render after collection fetch from JSON using jQuery in a require implementation
var appRouter = Backbone.Router.extend({
routes: {
"help": "help", // #help
},
help: function() {
/* Initialize the view passing the collection or initiallize the collection inside the view */
var view = new YourView({
collection: new YourCollection();
});
}
});
/*global define*/
define([
'jquery',
'underscore',
'backbone',
'models/YourModel'
], function($, _, Backbone, YourModel) {
'use strict';
var YourCollection = Backbone.Collection.extend({
model: YourModel,
url: './media/json/data.json',
getResults: function() {
var that = this;
this.fetch({
reset: true,
success: function( /*collection, response, options*/ ) {
that.trigger('successOnFetch');
},
error: function() {
that.trigger('errorOnFetch');
}
});
},
/*Parse function to point inside of the AJAX response variable*/
parse: function(result) {
return result.content;
}
});
return YourCollection;
});
define([
'jquery',
'underscore',
'backbone',
'handlebars',
'templates'
], function($, _, Backbone, Handlebars, foundation, ActiveClassHelper, JST) {
'use strict';
var clickEvent = (window.Modernizr.touch) ? 'touchend' : 'click';
var events = {};
var YourView = Backbone.View.extend({
template: JST['app/scripts/templates/NavigationTemplate.hbs'],
events: events,
initialize: function() {
//Listen to collection fetch to trigger error or render
this.listenTo(this.collection, 'successOnFetch', this.HandleSuccess);
this.listenTo(this.collection, 'errorOnFetch', this.HandleError);
this.collection.getResults();
},
HandleSuccess: function() {
this.render();
},
HandleError: function() {
console.log('We have an error fecthing collection');
},
render: function() {
this.$el.html(this.template(this.collection.toJSON()));
return this;
}
});
return YourView;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment