在主干视图的点击事件中创建新的主干视图

Create new Backbone Views in click event of Backbone View

本文关键字:视图 创建 事件      更新时间:2023-09-26

在PodcastView的点击事件中,我想创建多个新的PodcastItemView对象。jquery $.get 完美地工作,顺便说一句。

如果我在启动函数中执行console.debug(this.pinfo),我会收到我的播客项目的JSON数组(title,desc,url,...),所以这不是问题。此外,它通过此数组迭代 x 次,因此这也有效。

PodcastView = Backbone.View.extend({
    tagName: "li",
    itemTpl: _.template($("#podcast-item").html()),
    events: {
        "click .p-click" : "start"
    },
    initialize: function() {
        this.listenTo(this.model, "change", this.render);
    },
    render: function() {
        this.$el.html(this.itemTpl(this.model.toJSON()));
        return this;
    },
    start: function() {
        $.get(restUri + "podcast/" + this.model.get("title") + "/items", _.bind(function(data) {
            this.pinfo = data;
            _.each(this.pinfo, function(o) {
                var v = new PodcastItemView({model: o});
                $("#podcast-items").append(v.render().el);
            }, this);
        }));
    }
});

然而,不起作用的是创建新的PodcastItemView并将它们附加到 #podcast 项中。我收到以下错误:

TypeError: obj[implementation] 不是函数 (Backbone.js:225)

这是我的播客项目视图。

PodcastItemView = Backbone.View.extend({
        tagName: "div",
        itemTpl: _.template($("#podcast-item-list").html()),
        initialize: function() {
            this.listenTo(this.model, "change", this.render);
        },
        render: function() {
            this.$el.html(this.itemTpl(this.model.toJSON()));
            return this;
        }
    });

我感谢每一个提示或回复。

start函数重写为:

start: function() {
        $.get(restUri + "podcast/" + this.model.get("title") + "/items", _.bind(function(data) {
            this.pinfo = data;
            _.each(this.pinfo, function(o) {
                var model = new Backbone.Model(o)  
                var v = new PodcastItemView({model: model});
                $("#podcast-items").append(v.render().el);
            }, this);
        }));

如注释中所述,您的代码失败,因为您尝试将本机对象绑定到视图而不是 Backbone.Model。

希望这有帮助。