Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One modal rendering different templates when clicking on a element

I have different buttons (one for creating a 'sprint', another for creating a comment, etc). The forms for doing these tasks are appended to a modal dialog that is displayed when you click on the different buttons.

These are the flows:

click on "Sprint" button > append "Sprint" form > show the modal

then if you click on other button:

click on "Comment" button > empty modal content > append "Comment" form > show the modal

Currently, the different content is saved in a string and it is appended to the modal when you click the button.

But now I'm using Backbone and Underscore templates, and I can't figure out how to do the same thing. I don't want to have all the templates inside the modal and show them depending on the button you clicked; I want to append an already cached template on click.

Is there a way of doing this with Backbone and Underscore?

like image 406
Nico Echezarreta Avatar asked Oct 31 '12 17:10

Nico Echezarreta


1 Answers

Shvetusya has the general idea, but here's a specific example which will hopefully be clearer:

var Modal = Backbone.View.extend({
    render: function() {
        this.$el.append(this.options.form.render().$el);
    }
});

var SprintForm = Backbone.View.extend({
    render: function() {
        // Use your templating engine to make a "sprint" form
        // eg. this.$el.html(sprintTemplate());
    }
});

var CommentForm = Backbone.View.extend({
    render: function() {
        // Use your templating engine to make a "comment" form
        // eg. this.$el.html(commentTemplate());
    }
});

// handler for: click on "Sprint" button >
handleSprintButtonClick: function() {
    var sprintForm = new SprintForm();
    var modal = new Modal({form: sprintForm});
    $(document.body).append(modal.render().$el); 
}

// handler for: click on "Comment" button >
handleCommentButtonClick: function() {
    var commentForm = new CommentForm();
    var modal = new Modal({form: commentForm});
    $(document.body).append(modal.render().$el); 
}
like image 134
machineghost Avatar answered Oct 04 '22 21:10

machineghost