Skip to content

Instantly share code, notes, and snippets.

@usablewp
Created April 28, 2017 18:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save usablewp/7f24de7547ef962af75afe875ea122b0 to your computer and use it in GitHub Desktop.
Save usablewp/7f24de7547ef962af75afe875ea122b0 to your computer and use it in GitHub Desktop.
var testimonialsWidget = testimonialsWidget || {};
testimonialsWidget.render = function( id, JSON ){
// Model (Data for individual testimonial)
var Testimonial = Backbone.Model.extend( {
defaults: {
'quote' : '',
'author': ''
}
} );
// View ( Final markup for individual testimonial )
var TestimonialView = Backbone.View.extend( {
className: 'individual-testimonial',
events : {
'click .js-remove-testimonial' : 'destroy',
},
render : function(){
var tmpl = _.template( jQuery( '#js-testimonial-' + id ).html() );
this.$el.html( tmpl( this.model.toJSON() ) );
return this;
},
destroy : function(event){
event.preventDefault();
this.model.trigger( 'destroy' );
this.$el.remove();
}
} );
var TestimonialsView = Backbone.View.extend({
className: "testimonials",
el: '#js-testimonials-' + id,
events: {
'click .js-testimonials-add': 'addNew'
},
initialize: function( params ) {
console.log(this);
this.$testimonials = this.$( '#js-testimonials-list' );
this.collection.on( 'add', this.appendOne, this );
},
addNew : function( event ){
event.preventDefault();
console.log("inside Add One");
var testimonialId = 0;
if( ! this.collection.isEmpty() ){
var testimonialsWithMaxId = this.collection.max(function(testimonial){
return testimonial.id;
});
testimonialId = parseInt( testimonialsWithMaxId.id, 10 ) + 1;
}
this.collection.add( new Testimonial({ id: testimonialId }) );
return this;
},
appendOne: function( testimonial ){
var renderedTestimonial = new TestimonialView( { model: testimonial } ).render();
this.$testimonials.append(renderedTestimonial.el);
}
});
//Collection of testimonials
var Testimonials = Backbone.Collection.extend({
model: Testimonial
});
testimonials = new Testimonials();
// Collection of testimonials view
var testimonialsView = new TestimonialsView({
//el: '#js-testimonials-' + id,
collection: testimonials
});
testimonials.add(JSON);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment