将数据从模型传递到backbone.js中的视图

时间:2017-01-18 13:17:24

标签: backbone.js

我想将数据从模型传递到视图,我希望在视图中获取此数据长度并在其上进行循环但是长度属性未定义且我无法传递数据以查看模板中存在错误HTML

 <html>
<head>
    <link href='//fonts.googleapis.com/css?family=Lato:100' rel='stylesheet' type='text/css'>
</head>
<body>
    <div id="container">Loading...</div>
    <div class="list">
        <button id="list">LIST</button>
    </div>



      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
      <script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js" type="text/javascript"></script>
      <script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js" type="text/javascript"></script>
    <script type="text/template" id="view_list">


    </script>
    <script type="text/javascript">

    var app = {};
        app.postModel = Backbone.Model.extend({
            url: 'https://jsonplaceholder.typicode.com/comments',
            defaults: {
                postId: 0,
                id: 0,
                email:"",
                body:""
            }
        });

        app.viewlist = Backbone.View.extend({
            el:$(".list"),
            initialize:function(){
                this.model = new app.postModel();
            },
            template: _.template($('#view_list').html()),
            events:{
                "click #list"  : "list"
            },

            list:function(e)
            {
                this.model.fetch({
                    success: function (post) {

                        console.log(post.toJSON().length);
                        this.$el.html(this.template(post.toJSON()));
                    }
                });
            }


        });

        app.viewpost = new app.viewlist();


    </script>


</body>

并且html中的错误说

Uncaught TypeError: Cannot read property 'html' of undefined
    at success (backbone:49)
    at Object.a.success (backbone-min.js:12)
    at o (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at w (jquery.min.js:4)
    at XMLHttpRequest.d (jquery.min.js:4)

1 个答案:

答案 0 :(得分:2)

根据错误,看起来您没有在成功功能范围内拥有该视图。这应该有效:

            var view = this;
            this.model.fetch({
                success: function (post) {

                    console.log(post.toJSON().length);
                    view.$el.html(view.template(post.toJSON()));
                }
            });

虽然你应该考虑在视图中添加render函数,并且可能让视图监听模型更改以便触发它。

initialize: function() {
    this.model = new app.postModel();
    this.model.on('sync', this.render, this); // Backbone 0.9.2 way

    // Backbone 0.9.9+ way
    // this.listenTo(this.model, 'sync', this.render);
}

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

...

list: function(e) {
    this.model.fetch();
}