使用RequireJS初始化所有Backbone模型

时间:2015-10-14 09:33:36

标签: backbone.js requirejs marionette

我有一个用requirejs构建的骨干/牵线木偶项目。

define([
  'views/FormView',
  'path/to/Model',
], function (FormView, Model) {
  "use strict";

  return FormView.extend({

    model: new Model(),

    /* --- rest of view stuff --- */

  });
});

当页面加载时,项目中的所有模型都被初始化(即,将在所有模型上调用initialize()),但只有在控制器实例化视图时才会初始化视图。

这些模型只有在实例化后才会被初始化,这会让我感到很头疼。

有没有人遇到过这个?

更新

感谢Kevin和Yura的回答,这段代码有效:

define([
  'views/FormView',
  'path/to/Model',
], function (FormView, Model) {
  "use strict";

  return FormView.extend({

    model: undefined,

    initialize: function () {
      this.model = new Model();
    }

    /* --- rest of view stuff --- */

  });
});

2 个答案:

答案 0 :(得分:0)

模型只有在实例化后才能被初始化

根据定义,它们将是。

您正在上面的类定义中实例化模型,因此在定义FormView代码时会运行其初始化程序。您可能想要做的是在控制器中创建视图时将模型作为选项传递,例如:

var my_model = new Model();
var my_view = new FormView({model: my_model});

答案 1 :(得分:0)

你的问题是那个

model: new Model()
只要将requirejs模块加载到浏览器中,

就会立即运行。也就是说,当需要它时,它返回扩展的FormView,并且该原型用于FormView的所有实例。

此时实例化Model的新实例对象,并将同一实例用作model的每个新实例的FormView属性。

您可以做的不是直接使用FormView属性扩展model,而是将model实例创建委托给FormView实例的初始化:

define([
 'views/FormView',
 'path/to/Model', 
], function (FormView, Model) {   "use strict";

  return FormView.extend({

    initialize: function(){
      /* Create property `model` whenever new instance of FormView is created */
      this.model = new Model();
    }

    /* --- rest of view stuff --- */

  });
});

以下是完整的工作示例,以显示差异:

/** EXAMPLE 1 **
  Directly extending with `model` property and assigning 
  new instance of `Model`. Later you find out same model 
  instance is used for all `MyView` instances.
*/
var MyView = Backbone.View.extend({
  model: new Backbone.Model(),
  render: function(){
    this.$el.text('I am ' + this.model.get('name'));
  }
});

var myView1 = new MyView();
myView1.$el.appendTo(document.body);
var myView2 = new MyView();
myView2.$el.appendTo(document.body);

myView1.model.set({name: "Joe"});
myView2.model.set({name: "Bob"});

myView1.render();
myView2.render();

/** EXAMPLE 2 **
  Extending with `model` in initialize will create and assign
  new instance of `model` every time `MyOtherView` instance is created.
*/
var MyOtherView = Backbone.View.extend({
  initialize: function(){
    this.model = new Backbone.Model();
  },
  render: function(){
    this.$el.text('I am ' + this.model.get('name'));
  }
});

var myView1 = new MyOtherView();
myView1.$el.appendTo(document.body);
var myView2 = new MyOtherView();
myView2.$el.appendTo(document.body);

myView1.model.set({name: "Alice"});
myView2.model.set({name: "Catrine"});

myView1.render();
myView2.render();
<script src='http://code.jquery.com/jquery.js'></script>
<script src='http://underscorejs.org/underscore.js'></script>
<script src='http://backbonejs.org/backbone.js'></script>