【发布时间】:2014-02-17 05:01:44
【问题描述】:
Rails 应用在前端使用 Backbone。基本上我希望用户输入一个字符串并点击提交按钮。单击该按钮后,将更新两个视图。我从 SO 用户那里得到了一些很大的帮助,但遇到了另一个障碍。以下是详细信息:
我有两个模型,Publication 和 Article(带有相应的 Rails 模型)。我正在使用 gem (Feedzirra) 来解析用户输入的 RSS URL。因此,我将 url 发送到 /publications,并使用返回的数据获取 id,以便将其用作 POST 到 /articles 的输入。现在是时候重新渲染两个视图了。起初,我尝试使用 Backbones .sync 函数发出 POST 请求并让视图监听更改并相应地更新。但是,由于我需要来自一个请求的数据以便将其提供给下一个请求,因此我必须使用 $.post() 而不是 .sync。这主要是因为我不太了解如何使用.sync。使用 .sync 可以做到这一点吗?
这是 Backbone 中的文章视图:
SimpleGoogleReader.Views.ArticlesIndex = Backbone.View.extend({
template: JST['articles/index'],
el: '#article',
events:{
'click #new_feed': 'createFeed'
},
initialize: function() {
this.listenTo(this.model, "sync", this.render);
},
render: function(){
this.$el.html( this.template({articles: this.model.toJSON()}) );
return this;
},
createFeed: function(e){
e.preventDefault();
var feed_url = $('#new_feed_name').val();
$.post('/publications', {url: feed_url}, function(data){
$.post('/articles/force_update', {url: feed_url, publication_id: data.id}, function(data){
var publications = new SimpleGoogleReader.Collections.Publications();
publications.fetch({
success: function(publications){
var view = new SimpleGoogleReader.Views.PublicationsIndex({model: publications});
view.render();
}
});
});
}, 'json');
}
});
这是我在 Backbone 路由器中的 home 功能:
home: function(){
var publications = new SimpleGoogleReader.Collections.Publications();
var articles = new SimpleGoogleReader.Collections.Articles();
var pubIndex = new SimpleGoogleReader.Views.PublicationsIndex({model: publications});
var artIndex = new SimpleGoogleReader.Views.ArticlesIndex({model: articles});
articles.listenTo(publications, "change:shown", function(){
var articles = new SimpleGoogleReader.Collections.Articles();
articles.fetch({
success: function(articles){
var view = new SimpleGoogleReader.Views.ArticlesIndex({model: articles});
view.render();
}
});
});
publications.fetch();
articles.fetch();
},
我正在尝试的另一件事(您可以在此处看到)是继续使用 JQuery 嵌套 POST 请求,而不是使用 Backbone 的同步。一旦第二个返回,我重新渲染出版物视图。然后我只是让文章视图监听出版物视图的变化并在那时更新自己。根据我的发现,我认为您只能收听 Backbone 的模型更改,而不是视图更改。这是真的吗?
请指教!
【问题讨论】:
标签: javascript jquery ruby-on-rails post backbone.js