如何在模型中的.fetch()之后写入从服务器接收的数据并传递给模板?

时间:2013-12-25 16:32:37

标签: javascript backbone.js fetch

美好的一天!我是骨干的新手,我写了一个简单的基于应用程序的主干+ jquerymobile。 当我从服务器获取数据时,我需要将数据正确地传输到视图,然后将数据传递给模板。因为.fetch()异步,我无法传递渲染我的模型。如何从服务器收到.fetch()数据后,写入模型然后传递给模板?

//template
<script type="text/html" class="template" id="profile-form">
 <div data-role="header">
    <h3>Step 4</h3>
    <a href="#main" data-theme="a">Home</a>
    <a href="#logout" data-theme="a">logout</a>
 </div>
 <div data-role="content">
     <h2 class="ui-li-heading"><%= username %></h2>
     <p class="ui-li-desc"><strong><%= phone %></strong></p>
 </div>
</script>

// model
var UserInfo = Backbone.Model.extend({
url: appConfig.baseURL + "users/",
});

// routes
profileInfo: function () {
    var user = new UserInfo()
    this.changePage(new ProfilePageView({ model: user }));
},

// view
var ProfilePageView = Backbone.View.extend({

initialize: function () {
    this.template = $.tpl['profile-form'];
},

render: function (eventName) {
    $(that.el).html(that.template());
    return this;
}
});

我尝试在视图中添加此部件。它的作品,但我的风格不起作用。 我不太确定我通过在渲染中添加fetch来做正确的事情,可以建议如何正确地做到这一点吗?

    var that = this
    this.model.fetch({
        data: $.param({email: localStorage.getItem('user_email')}),
        type: 'POST',
        success: function (response) {
            $(that.el).html(that.template(JSON.parse(JSON.stringify(response))));
        }
    });

1 个答案:

答案 0 :(得分:2)

使用内置事件来解耦所有内容。获取是一步,更新是不同的。在你看来做:

initialize: function () {
    this.template = $('#profile-form').html();
    this.listenToOnce(this.model, 'sync', function(){ 
        this.render();
        //this.listenTo(this.model, 'change', this.render, this);
 }, this);
},

每次模型调用 set 方法(以及某些属性更改)时,都会触发更改事件。当发生这种情况时, listenTo 方法将运行回调。您可能需要的另一个事件是同步,这是在成功获取后调用的。有时您可能需要 listenToOnce ,如果您只想在第一个同步上呈现,然后自己控制它。

您的模板可能也需要传递参数:

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

就何时取得而言,这取决于你。您可以定期获取或仅在有人路由到该页面时获取。在你提供的代码中,我会做类似的事情:

profileInfo: function () {
    var user = new UserInfo();
    user.fetch();
    this.changePage(new ProfilePageView({ model: user }));
}