美好的一天!我是骨干网的新手,我写了一个基于骨干+ 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放入render中做正确的事,可以建议如何正确执行吗?

    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))));
        }
    });

最佳答案

使用内置事件解耦所有内容。提取是第一步,更新是独特的。您认为:

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 }));
}

关于javascript - 如何写在.fetch()之后从服务器接收的数据到模型中并传递给模板?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20774777/

10-11 01:23
查看更多