初始化中可访问的属性无法在模板中访问?

时间:2014-06-12 19:16:03

标签: javascript backbone.js

在实例化新视图时,我正在传递模型。我可以在“initialize”属性中访问该模型,但是当我尝试将模型传递到模板时,我无法引用它。知道为什么吗?

var postView = Backbone.View.extend({

        initialize : function() {

           // returns model 
            console.log('the model we are interested in',this.model); 
            this.render();
        },

        el : "#blog-post",

        template : function() {

            // returns undefined
            var model = this.model;

            return _.template($('#postview').html(), {
                post : model
            });
        },

        render : function() {
            var self = this;
            this.$el.html(self.template);
        }

    });

我在另一个视图中使用方法实例化它:

readMore : function(e, index) {
            var self = this;
            var newView = new postView({
                model : self.collection.models[index].toJSON()
            });

        }

3 个答案:

答案 0 :(得分:1)

您将某个功能传递给this.$el.html

this.$el.html(self.template);

这跟说:

var f = this.template;
this.$el.html(f);

那么html传递函数时会做什么?好吧,来自fine manual

  

.html(功能)

     

返回要设置的HTML内容的函数。收到索引   集合中元素的位置和旧的HTML值为   参数。 jQuery在调用函数之前清空元素;使用   oldhtml参数引用以前的内容。内   function,this指的是集合中的当前元素。

当您传递html函数时,它会调用该函数,但this不会是您认为的函数,函数内的this将是DOM元素正在设置HTML。

我想您想自己致电this.template并将其返回值交给html

this.$el.html(this.template());
// ------------------------^^

这样template会将视图视为this,与您期望的一样。

答案 1 :(得分:0)

最好的猜测是,这不再是指视图的上下文。如果你在函数中记录它显示的内容。

编辑 - 实际上不确定这是否会给出预期的结果,我通常使用把手,但我认为_.template和hanblebars的设置非常相似。您的模板模板通常需要传递给它的普通java对象,否则您必须访问您想要的变量,如post.attributes.name,但是如果您只是传递模型的toJSON版本,则可以访问属性而无需需要post.attributes。

此外,你可以编译你的模板一次然后只是引用它,不需要把它作为一个函数,并让它每次从DOM中获取(假设它永远不会改变)。以下是我的意思的一个例子。在您的模板中,您将拥有<%= name%>等抓住你的模型属性。     var postView = Backbone.View.extend({

        initialize : function() {

           // returns model 
            console.log('the model we are interested in',this.model); 
            this.render();
        },

        el : "#blog-post",

        template :  _.template($('#postview').html()),


        render : function() {

            this.$el.html(this.template(this.model.toJSON()));
            return this;

        }

    });

哦,通常的惯例是渲染返回'这个'因此,如果您想从其他地方调用它并将其附加到页面的新部分,您可以调用postView.render().el

答案 2 :(得分:-1)

您可能正在传递模型,但您未在视图中收到该模型。试试:

initialize: function(model) { ...
相关问题