假设我有一个Rails AR模型,如下所示
class User
has_one :profile
end
class Profile
belongs_to user
has_one :address
end
class Address
belongs_to :profile
end
并在客户端构建用户配置文件视图。现在,我的Backbone模型应该如何?它应该复制它在Rails /服务器端域模型中的方式吗?我们是否有明确的理由认为它必须是这样的,或者它只是主观的?
您的经验分享表示赞赏!
答案 0 :(得分:0)
为了简单起见,我认为模型应该代表服务器端模型和客户端视图状态,通过前面的_区分视图状态属性。保存模型时,服务器会忽略视图状态属性。
以下是我使用的工作流程的简化示例:
var animal = new View({
initialize: function(){
// define the model and default view state when view is initialized
this.model = new Model({id:3, _edit:false}, {url:'/animals'));
}
, render: function(){
var self = this;
this.undelegateEvents();
this.delegateEvents({
'click [data-trgger]': function(e){
self[$(e.currentTarget).attr('data-trigger')].apply(this);
}
});
var success = function(){
// pass the model to the template engine
self.$el.html( _.template('#edit-animals', {model: self.model}) );
}
// fetch the model from the server when view is rendered
// you could check if the model is already fetched
this.model.fetch({success:success});
}
, onSave: function(){
// save the model then:
this.model.set('_edit', false);
this.render();
}
, onEdit: function(){
this.model.set('_edit', true);
this.render();
}
});
模板:
<% if(model.get('_edit')){ %>
<!-- the view is in 'edit' state, show input and save button -->
<div>
<input type="text" name="breed" class="form-control">
</div>
<button class="btn btn-primary" data-trigger="onSave">Save</button>
<% }else{ %>
<!-- the view is in 'read-only' state, show values and edit button -->
<button class="btn btn-default" data-trigger="onEdit">Edit</button>
<div>
<%= model.get('breed') %>
</div>
<% } %>
答案 1 :(得分:0)
通常,您的主干模型和集合应遵循您的REST API(或任何其他客户端&lt; - &gt;服务器端通信)。
例如,如果将这些ruby模型传递给前端:
GET /api/user/:id
你得到的回应是
[{ profile: { address: "21st str." } },{ profile: { address: "17th str." } }]
你需要一个模型
User = Backbone.Model
Users = Backbone.Collection.extend({
model: User,
url: "/api/user"
});
但是,如果您在API中执行更复杂的操作并在API中添加更多网址,则可以选择最适合您与前端客户端交互的结构。例如,如果您的网站根本不需要用户API,并且您使用这些网址将数据传递到前端:
GET /api/profile
您只能拥有一个模型
ProfileModel = Backbone.Model.extend({
url: "/api/profile"
})
您可以轻松设置地址
profile = new ProfileModel();
profile.set('address', '21st str.');
底线
Backbone通常应该遵循REST API的URL结构。如果你这样做,你将享受使用正确自动配置的REST Ajax调用(GET,POST,DELETE,PUT)的全部好处。
通常我不做的是使我的Backbone应用程序结构遵循数据库架构。这可能会让您头疼,因为您需要创建一种后端(Ruby应用程序),以便能够提供与您正在使用的ORM几乎相同的数据库访问。