1 /** 2 * New comment creation button 3 * 4 * @class NewButtonView 5 * @extends Backbone.View 6 * @author Bodnar Istvan <istvan@gawker.com> 7 */ 8 /*global CommentModel, FormView */ 9 var NewButtonView = Backbone.View.extend( 10 /** @lends NewButtonView.prototype */ 11 { 12 /** 13 * The map of delegated event handlers 14 * @type Object 15 */ 16 events: { 17 'click': 'createComment' 18 }, 19 20 /** 21 * Initialize view, make sure button has a comment collection to work with 22 */ 23 initialize: function () { 24 if (this.collection === undefined) { 25 throw 'NoCollectionDefined'; 26 } 27 }, 28 29 /** 30 * Click event handler that first creates a new empty comment model, and assigns the model to a FormView instance. 31 * FormView will handle internally new comment creation and existing comment editing. 32 * @returns {Boolean} Returns false to stop propagation 33 */ 34 createComment: function () { 35 // create new comment model 36 var comment = new CommentModel({}); 37 38 // render form view right after new button 39 var formview = new FormView({model: comment}); 40 this.$el.after(formview.render().$el); 41 42 // add saved model to collection after form was submitted successfully 43 formview.on('success', this.handleFormSuccess, this); 44 45 // finally, return false to stop event propagation 46 return false; 47 }, 48 49 /** 50 * Method to handle FormView success event 51 * @param {CommentModel} model Model data returned by FormViews save request 52 */ 53 handleFormSuccess: function (model) { 54 this.collection.add(model); 55 } 56 57 } 58 );