Separate Backbone View functions into separate files

时间:2018-12-03 12:49:56

标签: javascript design-patterns backbone.js requirejs

I have a Backbone View.

To organize better the code of it, I would to prefer to separate some functions of it into a separate file.

So, I would like to maintains the structure but simply I need to separate the functions into different files:

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

I would like to use the view in the same current mode. So I need to call the functions 'A' on my view: myViewInstance.functionA_1()

What is the correct way/pattern to implement this?

I use also RequireJS.

1 个答案:

答案 0 :(得分:1)

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

像往常一样,将主体部分的原型成员添加到MyView的声明中:

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

将原型的其他部分放入单独的模块中,并将其导出为对象文字:

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

使主模块依赖于它们,并通过Object.assign_.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原型的其他部分,它依赖于其他两个模块:

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原型成员的对象:

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

myview-b.js导出对象与另一组MyView原型成员:

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