1

我正在使用主干 JS,我在显示模型中的数据时遇到了麻烦。谁能知道这是如何工作的?TIA

VIEW.JS -

    render: function() {
             ///EDITED TO SIMPLIFY      

            var toModel = new tModel();//tModel is the name of the model    
    console.log(toModel.get('data'));//?? UNDEFINE


  }

模型.JS——

    data:[
        { text: "Google", href: "http://google.com" },
        { text: "Facebook", href: "http://facebook.com" },
        { text: "Youtube", href: "http://youtube.com" }
    ],  
4

2 回答 2

2

http://jsfiddle.net/g3U7j/6/

模型.js

MyModel = Backbone.Model.extend({
    defaults: {
        data: [
            {
            text: "Google",
            href: "http://google.com"},
        {
            text: "Facebook",
            href: "http://facebook.com"},
        {
            text: "Youtube",
            href: "http://youtube.com"}
        ]
    }
});

视图.js

MyView = Backbone.View.extend({
    initialize: function() {
        var x = this.model.get('data');
        console.log(x);
    }
});

var View = new MyView({
    model: new MyModel
});​
于 2012-09-11T09:25:20.620 回答
0

它是this.model.get('data')(删除模型中的大写 M,它指的是类而不是实例成员)。

此外,如果您render直接从事件处理程序调用,则需要确保this在渲染方法中正确绑定到类实例(正常的东西使用that而不是this在 javascript 中;我主要在 Coffeescript 中这样做,这更容易一些)。

于 2012-09-11T09:07:28.763 回答