在不同视图之间共享相同的操作/功能

时间:2012-05-10 15:04:45

标签: javascript backbone.js

假设我对每个特定于项events: { "dblclick div.editable": "edit" }的DOM事件有不同的观点 我想在不同的视图之间共享函数edit(然后也保存)。

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
});

有可能吗?
什么是最好的方法?
有一些例子吗?

2 个答案:

答案 0 :(得分:2)

Backbone patterns site上介绍了如何使用 Mixins 解决此设计问题:

  

问题:有时候你有多个相同的功能   将对象包装在父对象中是没有意义的   宾语。例如,如果您有两个共享方法的视图,但是   不 - 也不应该 - 拥有共享的父视图。

     

解决方案:对于这种情况,使用mixin是合适的。

所以在这种情况下它可能是这样的:

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)

}));

答案 1 :(得分:1)

即使我认为@IntoTheVoid更优雅我想要揭示一个更简单的方法:一个Utils模块:

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" );
     }
});