Backbone.js TypeError:无法调用未定义的方法'on'

时间:2013-08-03 01:29:22

标签: backbone.js

我正在尝试学习Backbone.js。我正在尝试在视图中定义模型更改事件,但我收到以下javascript错误:     未捕获的TypeError:无法调用未定义的方法'on'

如果我从视图中取出初始化,它会显示文本而不会出错。

我是否拥有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();
 });

1 个答案:

答案 0 :(得分: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模型,那么您应该让它失败,这样您就不会忘记。