backbone.js模型属性未定义

时间:2013-03-02 03:23:20

标签: javascript jquery backbone.js

我从骨干网中的其他网址获取模型对象的集合。然后我迭代集合并使用下划线模板帮助方法来处理来自模型的数据。但是在调用属性时我得到了未定义的defaultImg。

查看:

 define (['jquery','underscore','backbone'],function($,_,Backbone){
PopVideoView = Backbone.View.extend ({
    tagName:"li",
    //template: _.template($('#popView').html()),
    template: _.template("<li><img src='<%= defaultImg %>'/></li>"),
    render: function ()
    {
        console.log(this.model.toJSON());
        this.template(this.model.toJSON());
        this.$el.html(this.template);
        return this;
    }
});
return PopVideoView;
});

另一种观点:

define(['jquery','underscore','backbone','collections/PopVideos','views/PopVideo'],function($,_,Backbone){
PopVideosView = Backbone.View.extend ({
    el:"#pop",
    render: function ()
    {
        this.collection.each (function(video)
        {
            popVideoView = new PopVideoView({model:video});
            this.$el.append (popVideoView.render().el).hide().fadeIn(300);
        },this);
        return this;
    },
});
return PopVideosView;
});

这是我从Chrome开发者控制台获得的内容:

Object {video_id: "1G4isv_Fylg", video_name: "Coldplay - Paradise ", defaultImg: "http://i.ytimg.com/vi/1G4isv_Fylg/mqdefault.jpg", genre: "pop", date: "Feb 16, 2013 1:01:33 PM"…}
Uncaught ReferenceError: defaultImg is not defined

我做错了什么?

这是模特&amp;系列:

 define (['jquery','underscore','backbone'],function($,_,Backbone){
Video = Backbone.Model.extend ({
    urlRoot:"/video",
});
return Video;
});//end define

define(['backbone','models/Video'],function(Backbone,Video) {
PopVideosCollection = Backbone.Collection.extend ({
    model:Video,
    url:"/pop/3/1"
});
return PopVideosCollection;
});

2 个答案:

答案 0 :(得分:1)

我发现问题我只需要这样做:

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

而不是:

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

答案 1 :(得分:1)

render中的PopVideoView方法存在一些问题:

template: _.template("<li><img src='<%= defaultImg %>'/></li>"),
render: function ()
{
    console.log(this.model.toJSON());
    this.template(this.model.toJSON());
    this.$el.html(this.template);
    return this;
}

当你致电_.template时,你会得到一个功能,所以:

this.template(this.model.toJSON());
除了你丢弃HTML返回值之外,

才有意义。这部分:

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

是你出错的地方,你将一个函数传递给jQuery的html方法和fine manual

  

.html(function(index,oldhtml))

     

功能(index,oldhtml)

     

返回要设置的HTML内容的函数。

所以jQuery使用它不理解的参数调用你的this.template函数。然后编译的模板函数在某个地方查找defaultImg,找不到它,并且因为没有ReferenceError而得到defaultImg

您不希望将该函数传递给html(),您希望评估模板函数并将其返回值传递给html()

render: function ()
{
    this.$el.html(this.template(this.model.toJSON()));
    return this;
}

顺便说一下,在定义视图和模型时,你真的应该使用var

define (['jquery','underscore','backbone'],function($,_,Backbone){
    var PopVideoView = Backbone.View.extend ({
    ^^^

如果你没有var,那些变量就是全局的。

相关问题