javascript - 将主干 View 功能分离到单独的文件中

标签 javascript design-patterns backbone.js requirejs

我有一个主干 View 。

为了更好地组织它的代码,我宁愿将它的一些功能分离到一个单独的文件中。

所以,我想维护结构,但我只需要将函数分离到不同的文件中:

- MyView
   - functions A -> file A;
   - functions B -> file B;

我想在相同的当前模式下使用 View 。所以我需要在我的 View 中调用函数“A”:myViewInstance.functionA_1()

实现它的正确方法/模式是什么?

我也使用 RequireJS。

最佳答案

您可以使用 Mixin pattern .将MyView的原型(prototype)划分为主体部分和其他部分,将它们放到独立的模块中,使主模块依赖于它们并将这些部分合并在一起。

照常将主体部分的原型(prototype)成员添加到 MyView 的声明中:

var MyView = Backbone.View.extend({
  method: function () {
    this.otherMethod();
  }
});

将原型(prototype)的其他部分放到单独的模块中并导出为对象字面量:

var prototypePart = {
  otherMethod: function () {}
};

使主模块依赖于它们并通过 Object.assign 合并所有导入部分的原型(prototype)或通过 _.extend :

// Merging the prototype with ES6.
Object.assign(MyView.prototype, prototypePart);
// Merging the prototype with Underscore.js.
_.extend(MyView.prototype, prototypePart);

您将获得 MyView 就像声明为“一体”:

var MyView = Backbone.View.extend({
  method: function () {
    this.otherMethod();
  },
  otherMethod: function () {}
});

例如,myview.js 导出MyView。它依赖于另外两个模块,以便从它们导入 MyView 原型(prototype)的其他部分:

define([
  'underscore', 'backbone', './myview-a', './myview-b'
], function (_, Backbone, myViewA, myViewB) {
  var MyView = Backbone.View.extend({
    // ...prototype members from this module
    initialize: function () {
      this.fromModuleA();
    }
  });
  // Add prototype members imported from other modules
  _.extend(MyView.prototype, myViewA);
  _.extend(MyView.prototype, myViewB);
  return MyView;
});

myview-a.js 导出带有一组附加 MyView 原型(prototype)成员的对象:

define(function () {
  var myViewA = {
    // ...prototype members from this module
    fromModuleA: function () {
      this.fromModuleB();
    }
  };
  return myViewA;
});

myview-b.js 使用另一组 MyView 原型(prototype)成员导出一个对象:

define(function () {
  var myViewB = {
    // ...prototype members from this module
    fromModuleB: function () {}
  };
  return myViewB;
});

关于javascript - 将主干 View 功能分离到单独的文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53594212/

相关文章:

javascript - 有条件地加载 jQuery 自定义脚本

javascript - Component-changes.json 未找到 SAPUI5

java - 设计问题: How to use composition the best

javascript - 如何在服务器上设置 "no value"以兼容Backbone?

javascript - 如何在最新的 Parse js sdk (1.6.2) 中实现 Backbone 模型?

javascript - rails : Make a div element visible/invisible with onchange after changing a collection_select field

javascript - typeahead - 从远程 URL 解析 json 数组

design-patterns - XML 序列化很慢

c++ - 多重继承和单例设计模式

javascript - backbone.js ajax 请求的全局错误处理程序