【问题标题】:Backbone.js TypeError: Cannot call method 'on' of undefinedBackbone.js TypeError:无法调用未定义的“on”方法
【发布时间】:2013-08-03 01:29:22
【问题描述】:

我正在尝试学习 Backbone.js。我正在尝试在视图中定义模型更改事件,但收到以下 javascript 错误: 未捕获的类型错误:无法调用未定义的“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();
 });

【问题讨论】:

    标签: backbone.js


    【解决方案1】:

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

    // 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 模型,您可能应该让它像那样失败,这样您就不会忘记。

    【讨论】:

    • 谢谢,您的建议效果很好,我更改了渲染功能。我试过:this.view = new ContentView({model: new Person()});作为一种替代方法。但这并没有响应更改事件。
    猜你喜欢
    • 1970-01-01
    • 2013-01-27
    • 2012-11-12
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多