1

我正在尝试学习 Backbone.js。我正在尝试在视图中定义模型更改事件,但收到以下 javascript 错误:Uncaught TypeError: Cannot call method 'on' of undefined

如果我从视图中取出初始化,它会显示没有错误的文本。

我的 Backbone 应用程序的基本结构是否正确?我究竟做错了什么?

$(document).ready(function rdy() 
{
    var Person = Backbone.Model.extend({
        defaults: {
            name:   'Alex',
            age:    33,
            }
        });

    person = new Person();

    var ContentView = Backbone.View.extend({
      el: '#content',
      initialize: function() {
        this.model.on('change', this.render, this);  //ERROR HERE <----------
        }, 
    render: function () {
        this.$el.html("Aargh Hello " + person.get('name'));
        return this;
        }
    });

  var NavigationRouter = Backbone.Router.extend({
    routes: {
        "": "defaultRoute"
            },
    initialize: function (options) {
        this.view = new ContentView({});          
        return this;
        },
    defaultRoute: function (actions) {
        this.view.render();
        }
  });
  var navigationRouter = new NavigationRouter;
  Backbone.history.start();
 });
4

1 回答 1

2

您需要将模型传递到视图中。喜欢:

// Pass in the person you made earlier. Alternatively, you could use
// new Person() instead of creating the person separately
this.view = new ContentView({ model: person });

那么你的渲染功能也应该使用this.model

您也可以在视图中进行检查,但如果视图将依赖于Person模型,您可能应该让它像那样失败,这样您就不会忘记。

于 2013-08-03T01:36:00.417 回答