Using backbone.js with jQuery UI Modals

In backbone, the views control all the events that are happening “in this part of html code” (in other words, your associated template). This is really good for decoupling your code and makes for a very good code structure but can be a headacke when trying to control popups.

Events in Backbone are handled automatically with jQuery delegates, thing is, the dom element that delegates all the events need to be outside the view or declared when the view is generated. This is a problem with modals because the element we are trying to delegate on is not in the view and needs to be called by jQuery UI on render.

Fortunately something you can do after your view content is rendered is changing the this.el element to the view container and call this.delegateEvents( . This will take care of the event binding problem.


wedapp.view.TasksForm = Backbone.View.extend({
	events: {
		"click #completedbtn" : 	"complete",
		"click #updatebtn" : 		"update",
		"click #savebtn" : 		"save",
		"click #closebtn" : 		"close",
	render: function() {
		var formString = this.template(this.model.toJSON());
			autoOpen: true,
			height: 460,
			width: 350,
			modal: true
		this.el = $(".dialogForm");
		return this;
	initialize : function(){
		this.template = _.template($("#task_form_tpl").html());
	complete: function(){
	update: function(){
	save: function(){
	close: function(){


That should help you get your popups going!

Cedric Dugas is an experienced front-end developer and founder of Position: Absolute, based in Montreal, Canada. When he is not doing CSS and jquery (does it ever happen?), he likes to read on web usability and play trumpet. Why don't you follow him on twitter.

4 Comments on "Using backbone.js with jQuery UI Modals"

  1. Ryan says:

    Thanks, this saved me a lot of angst! It works great with Facebox – here’s a coffeescript example:

    html = @template()
    @el = $(“#facebox”)

  2. Veera says:

    Whoa! Saved my day. I was trying to integrate JQuery Simple Modal and having issues with event delegation. This post just helped me to resolve the issue.

    Thanks a lot.

  3. zkov says:

    I am trying to get up to speed on backbone and jquery and just curios where did you declared your dialogForm and whether you have source code for this?!

Trackbacks for this post

  1. Backbone.js and JQueryUI Dialog – events not binding | PHP Developer Resource

Got something to say? Go for it!