2

我目前正在学习主干,并面临以下问题。我想将新元素附加到视图的 this.el 元素。但它不会发生。这是我的代码:

var MyData = Backbone.Model.extend({
    initialize: function() {
        this.bind('error', function(model, error) {
            console.log('error:' + error);
        });
    },
    defaults: {
        name: "Jo",
        age: 18,
        skill: 0
    },
    validate: function(attributes) {
        if (attributes.name == "Jonh")
            return false;
        return true;
    }
});

var MyView1 = Backbone.View.extend({
    initialize: function() {
        this.$el.empty();
    },
    el: '#middle',
    events: {
        "click": "render"
    },
    render: function() {
        this.$el.append(this.model.get('name'));    
    }
});

var myData = new MyData();
var myView1 = new MyView1( {model: myData} );

在 html 文件中有一个 div 元素定义如下:

<div id="middle"></div>

该代码可以正常工作,但我没有看到任何附加元素。我也尝试过像这样附加:

this.$el.append($("<p>").append(this.model.get('name')));   
4

2 回答 2

6

Since your javascript script loads before the page is loaded, Backbone View can't see #middle div, so you have to initialize views after page is loaded:

$(document).ready(function() {
    // load your views
});
于 2013-06-01T12:06:53.030 回答
1

我刚刚在我的 IDE 中加载了它,它运行良好。您的控制台没有显示任何错误?

于 2013-06-01T11:20:58.903 回答