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.events) . This will take care of the event binding problem.

Example

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());
		$(formString).dialog({
			autoOpen: true,
			height: 460,
			width: 350,
			title:"Tasks",
			modal: true
		})
		this.el = $(".dialogForm");
		this.delegateEvents(this.events)
		return this;
	},
	initialize : function(){
		_.bindAll(this,"render")
		this.template = _.template($("#task_form_tpl").html());
		this.render().el;
	},
	complete: function(){
		console.log("test")
	},
	update: function(){
		console.log("test")
	},
	save: function(){
		console.log("test")
	},
	close: function(){
		console.log("test")
	},
});

“Voila!”

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()
    $.facebox(html)
    @el = $(“#facebox”)
    @delegateEvents(@events)

  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!