主干视图未捕获引用错误

Backbone View Uncaught Reference Error

本文关键字:引用 错误 视图      更新时间:2023-09-26

如果您能帮助我理解为什么我会得到一个未捕获的参考错误(请参阅下面的代码)。从本质上讲,在视图初始化时,我正在获取一个模型将"this.model"(实例模型)传递给模板。在所有其他视图中,即使实例模型未定义未捕获的引用错误不会引发。有人知道吗为什么把它扔在这里?

Views.Projects.EditView = Backbone.View.extend({
    tagName: 'div',
    id: 'edit-project-content',
    template: JST['projects/edit'],
    initialize: function(){
        this.model = new Models.Project({id: this.options.projectId});
        this.model.bind('change', this.render, this);
        this.model.fetch({
            error: function(model, response) { alert('Error...Please try again.'); }
        });
    },
    render: function() {
        $(this.el).html(this.template({project: this.model})); // Error references this line.
        return this;
    }
});

模板:

<% if (typeof project != 'undefined') { %>
<div id="edit-details">
    <form id="edit-project-form">
        <ul>
            <li>
                <p class='form-title'>Edit Project: "<%= project.get('title') %>"</p>
            </li>
            <li>
                <label for='project-title'>Project Title:</label>
                <input id='project-title' type='text' value="<%= project.get('title') %>" />
            </li>
            <li>
                <label for='due-date'>Due Date:</label>
                <input id='due-date' type='text'></input>
            </li>
            <li>
                <label for='project-description'>Description:</label>
                <textarea id='project-description'><%= project.get('description') %></textarea>
            </li>
            <li>
                <input id='submit-project-edits' type='submit' value='Edit' />
            </li>
        </ul>
    </form>
</div>
<% } %>

谢谢。

试试这个:

render: function() {
    model = this.model;
    $(this.el).html(this.template({project: model})); // Error references this line.
    return this;
}

您可以更改

<% if (typeof project != 'undefined') { %>

<% if( project != null ) { %>

<% if( project ) { %>

请参阅https://developer.mozilla.org/en/JavaScript/Reference/Operators/typeof

typeof undefined === 'undefined'
typeof null === 'object'

试图访问null或未定义的属性将在JS中引发异常。(我有时有点怀念ActionScript 2:)

我复制了您的代码,当我在控制台中调试它时,我得到了以下错误。

未捕获类型错误:对象#没有方法"get"

我在控制台中看到了"项目"模型,它正在将模型绑定到模板。如果你能复制的话,这可能是你这边的一条线索

我的申请中也遇到了同样的问题,这就是我所做的,它起到了作用。我必须在视图中指定模型的类型,它起作用了。试试看是否有帮助。希望能有所帮助。

Views.Projects.EditView = Backbone.View.extend({
    tagName: 'div',
    **model : your model**
    id: 'edit-project-content',
    template: JST['projects/edit'],
    initialize: function(){
        this.model = new Models.Project({id: this.options.projectId});
        this.model.bind('change', this.render, this);
        this.model.fetch({
            error: function(model, response) { alert('Error...Please try again.'); }
        });
    },
    render: function() {
        $(this.el).html(this.template({project: this.model})); // Error references this line.
        return this;
    }
});