BackBoneJS哪一个是最好的方法?获取+成功或绑定chage

时间:2017-03-27 09:43:14

标签: javascript json ajax backbone.js

我有一个Backbone应用程序,我从后端API获取BackBone View中的数据,然后调用函数render以使用我获得的数据呈现模板。

我想知道哪一个是获取和渲染的最佳实践,为什么?

1-使用提取,然后在render上致电success

define(
    ['models/object',
        'text!templates/home.html',
        'backbone'
    ],
    function(ObjectModel, HomeTemplate, Backbone) {
        var homeView = Backbone.View.extend({

            initialize: function(options) {
                var self = this;
                this.homeTemplate = _.template(HomeTemplate);

                this.object = new ObjectModel({
                    id: <ANY_ID>
                }); 

                this.object.fetch({
                    success: function() {
                        self.render(self.object);
                    }
                });

            },
            render: function(data) {
                this.$el.html(this.homeTemplate);
                console.log(data);
                return this;
            },

        });

        return homeView;

    });

2-当objects更改为render后绑定:

define(
    ['models/object',
        'text!templates/home.html',
        'backbone'
    ],
    function(ObjectModel, HomeTemplate, Backbone) {
        var homeView = Backbone.View.extend({
            initialize: function(options) {
                var self = this;
                this.homeTemplate = _.template(HomeTemplate);

                this.object = new ObjectModel({
                    id: <ANY_ID>
                });

                this.object.bind('change', this.render, this);
                this.object.fetch()

            },
            render: function(data) {
                this.$el.html(this.homeTemplate);
                console.log(data);
                return this;
            },

        });

        return homeView;

    });

0 个答案:

没有答案