0

I have a custom jQuery widget that is being called from my app that uses backbone.js for MVC. How can I use the backbone events pattern in my custom jQuery widget?

function( $ ) {
  $.widget( "medex.chooser", {
  ...
  _create: function() {
      // Would I create a new backbone view here???
  }
}

Thanks.

Ramya
  • 289
  • 6
  • 17
  • Why not create the view normally but give it the widget's `element`: `new View({ el: this.element })`? – mu is too short Jun 05 '12 at 21:30
  • Thanks but I want the custom widget to handle the events. – Ramya Jun 05 '12 at 22:44
  • So is the widget the view? The widget contains the view? The view contains the widget? Or something else? – mu is too short Jun 05 '12 at 22:52
  • That was my question. Should the widget contain the view? The widget basically lays out 2 jqgrids side by side and allows users to move rows from one to another. I was wondering if there is a best practice to create a view within the widget -- maybe I am over thinking this. – Ramya Jun 06 '12 at 18:24

2 Answers2

0

I think you need to define a custom View that is then called by your custom widget.

In your app initialization code, for example:

APP = {};          // your app's global object
APP.Views = {};

APP.Views.WidgetView = Backbone.View.extend(
{
    events: {
        "click .grid1" : "onGrid1Click"
    },

    initialize: function() {
        // code here
    },

    onGrid1Click : function(evt) {
        // code here
    }
});

Then this will be the constructor code for your widget:

function Widget(element) {
   this.view = new APP.Views.WidgetView({ el: element });
}

This code might not be entirely valid, but should give you an idea of the structure you were looking for. Lemme know if this works for you.

sirentian
  • 187
  • 1
  • 2
  • 9
0

If you're still looking for an answer, you could convert a widget into a view. The basic rules for converting from a Widget to a View are these:

  • _create becomes initialize
  • this.element becomes this.$el
  • refresh becomes render
  • destroy becomes remove
  • $('.someDiv').myWidget() becomes new MyView({ el: $('.someDiv') });
  • options have to become constructor parameters, but can be handled a couple of different ways
Alex Shilman
  • 1,547
  • 1
  • 11
  • 15