jax
jax

Reputation: 38633

questions about backbone.js integration with JQuery/JQueryUI

I have just started using backbone (with requirejs for modules).

It seems to me that there is an overlap between what jQuery can do and what Backbone can do. This leaves me wondering which option I should be using.

For example, I could listen to an even in the following ways:

$('selector').click( function(event) {...

or

var myView = Backbone.View.extend({
  events: {
    "click selector": "onClickSelector",
  }, ...

1) Which of the above options should I be using?

Jquery supports things that I just don't know how to manage with Backbone. For example, the autocomplete function of JqueryUI:

$('selector').autocomplete({ ...

2) how might I implement autocomplete this using backbone? Do I just do all this in a method after the view is rendered onPostRender()?

I find see a lot of example that seem to add new members to the View object. For example:

var myView = Backbone.View.extend({
  events: {
    deletePressed: function() { ... },
    submitPressed: function() { ... },
    editPressed: function() { ... },
  }, ...

if the functionality of these events is simple, I can see that this makes sense, however, if there is more complexity to the behaviour the View object will get very complex.

3) Should I be implementing complex behaviour in the anonymous function or should I call a named function?

4) Kind of similar to the above, if I have a common function that is used by many events (such as resetForm()) should this be declared as a member of the View of a names function?

I am currently storing my jquery objects as variables in the module

var $mySelector = $(selector);

or I could attach them to the View

var myView = Backbone.View.extend({
  initialize: {
    this.mySelector = $(selector);
  }, ...

5) Should I be making my JQuery objects part of the View or part of the AMD module:

Upvotes: 1

Views: 112

Answers (1)

Niranjan Borawake
Niranjan Borawake

Reputation: 1638

Here are answers to your questions:

1 : Go for the second option the one with events property in the view. Note : You can bind events using this approach to only those elements which are children of the element you specified as el in your view.

2: Yes you can do it in onPostRender().

3: If you want handleDeletePressed(), handleSubmitPressed() and handleEditPressed() to be reused or they have to do lot many things I suggest it is better to create named functions and specify them as :

events: {
    deletePressed: 'handleDeletePressed',
    submitPressed: 'handleSubmitPressed',
    editPressed: 'handleEditPressed',
  }

4: You can declare it as a member of view.

5: At any instance inside your view you can use this.$('selector'), to get jQuery object. If you want you can create jQuery objects as well.

Upvotes: 1

Related Questions