如何在Backbone.js中获取视图中的模型属性?

时间:2012-12-17 14:32:45

标签: javascript rest backbone.js

我正在尝试将模型作为参数传递给视图。 我在视图中获取对象,但无法访问其属性... 这是代码:

来自路由器:

var Product = new ProductModel({id: id});
Product.fetch();
var product_view = new ProductView({el: $("#main-content"), model: Product});

从模型中:

var ProductModel = Backbone.Model.extend({
urlRoot: 'http://192.168.1.200:8080/store/rest/product/'
});

从视图:

ProductView = Backbone.View.extend({
    initialize: function(){
        console.log(this.model);
        this.render();
    },
    render: function(){
        var options = {
            id: this.model.id,
            name: this.model.get('name'),
            publication_start_date: this.model.get('publication_start_date'),
            publication_end_date: this.model.get('publication_end_date'),
            description: this.model.get('description'),
            applis_more: this.model.get('applis_more')
        }
        var element = this.$el;
        var that = this;
        $.get('templates/product.html', function(data){
            var template = _.template(data, options);
            element.html(template);
        });
    }
});

以下是“console.log”的结果:

child {attributes: Object, _escapedAttributes: Object, cid: "c1", changed: Object, _silent: Object…}
Competences: child
Editor: child
Hobbies: child
Opinions: child
_changing: false
_escapedAttributes: Object
_pending: Object
_previousAttributes: Object
_silent: Object
attributes: Object
createdDate: null
deletedDate: null
descriptionId: 0
galleryImage: null
id: 13
image: null
manufacturerId: 0
name: "sdf"
owner: 0
status: 0
thumbnail: null
titleId: 0
type: 1
uid: "fdsf"
updatedDate: null
__proto__: Object
changed: Object
cid: "c1"
id: 13
__proto__: ctor

在我看来,我的所有选项都是“未定义”(名称,日期,......)

对我做错了什么的想法?

3 个答案:

答案 0 :(得分:6)

创建初始模型后,您将立即使用

创建视图
var product_view = new ProductView({..., model: Product});

initialize的{​​{1}}方法中,您正在调用ProductView,而this.render()则会从模型中读取和呈现值 - 这些值中的大多数都是undefined(因为服务器没有足够的时间发回模型的值 不要直接调用this.render(),而是绑定事件,例如:

// in ProductView::initialize
this.model.on('sync', function() {
    this.render();
}, this);

您可能还想绑定change事件,以便对模型的本地(尚未同步)更改也会反映在视图中。 (可以找到Backbone事件的概述here。)

答案 1 :(得分:2)

因为Product.fetch()是异步发生的,所以一旦从服务器检索到数据,你就会想要创建视图:

var Product = new ProductModel({id: id});
var product_view;
Product.fetch().done(function() {
    product_view = new ProductView({el: $("#main-content"), model: Product});
});

答案 2 :(得分:1)

Product.fetch()是一个异步调用,所以我猜测初始化视图时fetch还没有完成。您可能想要做的是使用fetch的成功+错误回调,以确保模型在呈现任何内容之前包含数据

http://backbonejs.org/#Model-fetch