骨干:传递模型属性给视图返回未定义

Backbone: Pass Model Attribute to a View returns undefined

本文关键字:视图 返回 未定义 属性 模型 骨干      更新时间:2023-09-26
var ShapeSizePoolView = Backbone.View.extend({
    el : $('#agpb_shape_size_body'),    
    tmpl : $('#tmpl_agpb_shape_size').html(),
    initialize : function() {
        this.render();
    },
    render : function() {
        var compiled_template = _.template( this.tmpl, this.model.toJSON() ),
            sizes = this.model.get('sizes');
        $(this.el).append( compiled_template );
        // this is used for our pool sizes
        for(var i = 0; i < sizes.length; i++) {
            console.log(sizes[i]);
            new ShapeSizePoolButtonView(
            { 
                size : sizes[i],
                el : $(this.el).find('.agpb_size_list')
            });
        }
    }
});
var ShapeSizePoolButtonView = Backbone.View.extend({
    tmpl : $('.tmpl_agpb_shape_size_button').html(),
    initialize : function() {
        // this.render();
        console.log( this.size );
        },
        render : function() {
            var compiled_template = _.template( this.tmpl, this.sizes );
            $(this.el).append( compiled_template );
        }
});

this.model.get('sizes')返回一个对象数组。如果我输入console。log ShapeSizePoolView中的一个对象我得到:

{
    id: "6", 
    dimensions: "12'",
    price: "649.99", 
    sort_order: "1"
} 

我将这个对象传递给一个新视图,但是如果我console.log this。size from ShapeSizePoolButtonView我得到:

undefined

有谁知道我哪里错了吗?

谢谢!

From the Backbone docs:

创建新视图时,合并后传递的选项添加到视图上已存在的任何默认选项中观点是这样的。供将来参考的选项。有几个特殊选项,如果传递,将直接附加到视图:模型、集合、el、id、className、tagName和属性。

因此,您可以使用this.options: 访问这个自定义选项。
var ShapeSizePoolButtonView = Backbone.View.extend({
    tmpl : $('.tmpl_agpb_shape_size_button').html(),
    initialize : function() {
        // this.render();
        console.log( this.options.size ); // Not this.size
    },
    ....
});

您将size传递给View构造函数,但它不会自动复制到this上。您需要添加如下代码:

var ShapeSizePoolButtonView = Backbone.View.extend({
  initialize : function(options) {
    this.size = options.size;
    // this.render();
    console.log( this.size );
  },

另外,您在渲染调用中错误地使用this.sizes而不是this.size