javascript - 如何在 Backbone.js 的 View 中获取模型属性?

标签 javascript rest backbone.js

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

从路由器:

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/'
});

从 View :

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

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

知道我做错了什么吗?

最佳答案

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

var product_view = new ProductView({..., model: Product});

ProductViewinitialize 方法中,您正在调用 this.render(),它依次从模型 - 这些值中的大部分都是未定义(因为服务器没有足够的时间发回模型的值)。
不要直接调用this.render(),而是绑定(bind)一个事件,eg:

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

您可能还想绑定(bind) change 事件,以便对模型进行的本地(尚未同步)更改也反射(reflect)在 View 中。 (可以找到 Backbone 事件的概述 here。)

关于javascript - 如何在 Backbone.js 的 View 中获取模型属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13916095/

相关文章:

javascript - Office插件开发: Insert table in Word 2016

linux - 将 curl REST API 调用重定向到文件不适用于大负载

session - 配置两个cxf jaxrs客户端以使用相同的 session (cookie)

java - MessageBodyReaders 如何使用

javascript - 在backbone.js中验证模型

backbone.js - Backbone.Collection.Create 在 View 中未触发 "add"

javascript - 如何使表格内的内容(Fusion Chart LED 仪表图)具有响应性?

javascript - 在 JavaScript 中操作数组

javascript - 通过模型Backbone更新变量

javascript - 使用 Angular 模板生成可导出的 HTML