underscore666
underscore666

Reputation: 1739

Share the same action/function between different views

Let's suppose I have different views each of them with the DOM events specific to an item events: { "dblclick div.editable": "edit" }
I want to share the function edit (and then also save) between different views.

var View1 = Backbone.View.extend({

     events: { "dblclick div.editable": "edit" },

     edit: function () {} // function I would like to share btw diff views
});

var View2 = Backbone.View.extend({

     events: { "dblclick div.editable": "edit" },

     edit: function () {} // function I would like to share btw diff views
});

It will be possible?
What is the best approach?
Are there some examples?

Upvotes: 0

Views: 95

Answers (2)

fguillen
fguillen

Reputation: 38772

Even I think the @IntoTheVoid is more elegant I wanted to expose a very simpler approach: an Utils module:

var App = function(){};

App.Utils = {
  myCommonFunction: function( param ){ 
    // code 
  }
}

var View1 = Backbone.View.extend({
     events: { "dblclick div.editable": "edit" },
     edit: function() {
       App.Utils.myCommonFunction( "param" );
     }
});

var View2 = Backbone.View.extend({
     events: { "dblclick div.editable": "edit" },
     edit: function() {
       App.Utils.myCommonFunction( "param" );
     }
});

Upvotes: 1

user920041
user920041

Reputation:

On the Backbone patterns site it is described how to use Mixins to solve this case of design issue:

The problem: Sometimes you have the same functionality for multiple objects and it doesn't make sense to wrap your objects in a parent object. For example, if you have two views that share methods but don't -- and shouldn't -- have a shared parent view.

The solution: For this scenario, it's appropriate to use a mixin.

So in this case it could be something like this:

App.Mixins.Editable = {
  edit: function() { /* ... */ },

  open: function() { /*... */ },

  close: function() { /* ... */ }
};

App.Views.YourEditPage = Backbone.View.extend(
  _.extend({}, App.Mixins.Editable, {

   events: { "dblclick div.editable": "edit" },

  // (Methods and attributes here)

}));

Upvotes: 2

Related Questions