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

Share the same action/function between different views

本文关键字:操作 功能 之间 视图 共享      更新时间:2023-09-26

假设我对特定于项目的 DOM 事件有不同的视图events: { "dblclick div.editable": "edit" }
我想在不同的视图之间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
});

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

在主干模式站点上描述了如何使用 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)
}));

即使我认为@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" );
     }
});