CamelCamelCamel
CamelCamelCamel

Reputation: 5200

Backbone :: Using jQuery Plugins on Views

I'm having trouble figuring out a clean way to do this. Let's take for an example a code snippet from the example todo app that comes with backbone:

addOne: function(todo) {
  var view = new TodoView({model: todo});
  $("#todo-list").append(view.render().el);
},

So the ToDo view is being rendered and then it's being appended to #todo-list. But let's suppose we want to add a jQuery plugin to ToDo view. Where should we place the $(".todo").plugin() snippet? If we place it inside the ToDo view render function the HTML element is not set on the page, so the plugin won't 'latch' to any DOM element. If we place this inside the addOne function it will look ugly.

So, what's the best way?

Upvotes: 2

Views: 4113

Answers (2)

Tom Tu
Tom Tu

Reputation: 9593

You can use the backbone $ method like so this.$('todo') to use context scoped jquery querying which will allow you to search in the current view DOM fragment which wasn't added to the document DOM tree yet.

From my experience adding jquery plugin binding in either render method or some kind of helper function if there was more custom bindings which would be then called from render method after the template was created.

Upvotes: 1

Derick Bailey
Derick Bailey

Reputation: 72878

The answer largely depends on the plugin you're talking about.

For example, most of the jQueryUI controls and the KendoUI controls allow you to call the plugin method from the render of the view, directly, before the HTML is attached to the DOM. You simply call it on the view's el.

For example, if I wanted to use KendoUI's menu on a view that generated:


Backbone.View.extend({
  tagName: "ul",

  render: function(){
    var html = "<li>foo</li><li>bar</li>"; 
    this.$el.html(html);
    this.$el.kendoMenu();
  }
});

There are some plugins that require the HTML to be a part of the DOM already, for whatever reason. In this case, I typically provide an onShow function in my views, and have the code that is displaying the view check for this and call it if it exists.

For example, there's a "Layout" plugin that I've used a few times. This plugin requires the HTML to be part of the DOM before it can work:


MyView = Backbone.View.extend({
  render: function(){
    var html = "generate some html here...";
    this.$el.html(html);
  },

  onShow: function(){
    this.$el.layout();
  }
});

// .... some other place where the view is used

var view = new MyView();
view.render();

$("#someElement").html(view.el);

if (view.onShow) {
  view.onShow();
}

FWIW: I've written the code for onShow and other common methods and events dozens of times, and have consolidated it all into a Backbone add-on called Backbone.Marionette, so that I don't have to write it anymore.

http://github.com/derickbailey/backbone.marionette

There's a lot more than just this available in this add-on, of course.

Upvotes: 6

Related Questions