簡體   English   中英

如何在Backbone.js中獲取視圖中的模型屬性?

[英]How to get model attributes within a view in 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

在我看來,我的所有選項都是“未定義”(名稱,日期,......)

對我做錯了什么的想法?

創建初始模型后,您將立即使用創建視圖

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

ProductViewinitialize方法中,您調用this.render() ,然后從模型中讀取和呈現值 - 這些值中的大部分都是undefined (因為服務器沒有足夠的時間來發回模型的值) 。
不要直接調用this.render() ,而是綁定一個事件,例如:

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

您可能還希望綁定change事件,以便對模型的本地(尚未同步)更改也反映在視圖中。 (可以在此處找到Backbone事件的概述。)

因為Product.fetch()是異步發生的,所以一旦從服務器檢索到數據,您就會想要創建視圖:

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

Product.fetch()是一個異步調用,所以我猜測初始化視圖時fetch還沒有完成。 您可能想要做的是使用fetch的成功+錯誤回調,以確保模型在呈現任何內容之前包含數據

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM