为什么我的Backbone.js代码段找不到DOM模型?

How come my Backbone.js snippet can't find a DOM model?

本文关键字:找不到 DOM 模型 代码 我的 Backbone js 为什么      更新时间:2023-09-26

看看下面的代码片段:

<script>
$(function(){
    var to_username = "alex";
    window.Persona = Backbone.Model.extend({
    }); 
    window.PersonaList = Backbone.Collection.extend({
        model:Persona,
        url:function(){
            return '/js/personas/approval/user?to_username=' + to_username;
        }
    }); 
    window.Personas = new PersonaList;
    window.CheckView = Backbone.View.extend({
        tagName:'div',
        template: _.template($("#checkbox_friends").html()),
        initialize: function(){
            this.model.bind('change', this.render, this);
        },
        render:function(){
            $(this.el).html(this.template({}));
            return this;
        }
    }); 
    window.AppView = Backbone.View.extend({
        el:$("#add_friend_holder"),
        coreTemplate: _.template($("#add_friend_templ").html()),
        initialize:function(){ 
            this.render();
            Personas.bind('reset', this.addAllBoxes, this);
            Personas.bind('all',this.render, this);
            Personas.fetch({
                success:function(){ 
                },
                error:function(){
                }
            });  
        },
        addOneBox:function(persona){
            var check_view = new CheckView({'model':persona});
            this.$("#friend_ticker").append(check_view.render().el); //DOESNT APPEND!!!
        },
        addAllBoxes:function(){
            Personas.each(this.addOneBox);
        },
        render:function(){
            this.el.html(this.coreTemplate({}));
        }
    });
    window.App = new AppView;
});
</script>
<div id="add_friend_holder"></div>
<style>
    #friend_ticker{
        padding:6px;
        border:1px solid #ccc;
        background:#fff;
        width:200px;
    }
</style>
<script type="text/template" id="add_friend_templ">
    <button class="btn danger">Add Friend</button>
    <div id="friend_ticker">
    </div>
</script>
<script type="text/template" id="checkbox_friends">
    <input type="checkbox">
    Print this
</script>

一切正常,除了一行:

this.$("#friend_ticker").append(check_view.render().el);

如果我console.log(check_view.render().el) ....一切都很好。

除了,我的脚本没有找到这个。$("#friend_ticker"),即使它就在那里。

可能是你绑定到两个Collection事件后,在获取后渲染视图2次。

Personas.bind('reset', this.addAllBoxes, this);
Personas.bind('all',this.render, this);

第一个调用用子模板填充视图。第二种方法将父元素再次呈现为空。

ProTom是正确的,视图被渲染了两次。也许你想绑定到集合的"add"事件而不是"all"。

这里有一个jsfiddle作为视图呈现的示例,我手动向列表添加了一个项目,并绑定了集合的add事件。另外,我把

注释掉了
   Personas.bind('all',this.render, this); 

如果你取消那一行的注释,你会看到你的渲染事件被触发两次,并"擦除"div的内容