如何构造backbone.js使其返回模板+;数据和(考虑到基于登录的重新路由)
我正在构建一个小应用程序,它在客户端使用backbone.js,在服务器端使用node.js/socket.io,并且只通过WebSocket进行连接 现在,如果我想同时获得模板和数据,我将如何进行设置如何构造backbone.js使其返回模板+;数据和(考虑到基于登录的重新路由),backbone.js,Backbone.js,我正在构建一个小应用程序,它在客户端使用backbone.js,在服务器端使用node.js/socket.io,并且只通过WebSocket进行连接 现在,如果我想同时获得模板和数据,我将如何进行设置 我在路由器中执行fetch(),获取数据和模板。通过这个,我构建了我的视图->集合->模型 我在视图本身中执行fetch()。(可能在初始化中) === 我想用以下内容扩展这个问题 假设用户浏览到http://mysite.com/products如果用户尚未登录,则不允许他查看该页面。他必须被
fetch()
,获取数据和模板。通过这个,我构建了我的视图->集合->模型fetch()
。(可能在初始化中)http://mysite.com/products
如果用户尚未登录,则不允许他查看该页面。他必须被重新路由到/login
问题是我只能在服务器上验证这一点,因此无论用户是否登录,服务器都必须发回正确的数据,backbone.js必须处理这一问题
总结:我提取到服务器,服务器将发送回数据+模板html Backbone.js必须使用数据呈现模板
或者在服务器发回标志时重新路由(
Backbone.history.navigate('login',{trigger:true})
。您可以在主干集合中使用parse方法,例如:
Collections.Products = Backbone.Collection.extend({
url : '/products',
parse : function (response) {
//
// you should return JSON from your server and the object must be smth like
// { template : "<p>template for products</p>", data : productsInJSON }
//
if ( response.template && response.data ) {
this.trigger('template', response.template);
return response.data;
} else {
return response;
}
}
});
Views.Page = Backbone.View.extend({
initialize : function () {
_.bind(this, 'render');
var self = this;
this.collection = new Collections.Products();
this.collection.on('template', function(template) {
self.render(template);
});
},
render: function(template) {
$("div#page").html(template);
}
});
$(function() {
window.app = {};
window.app.view = new Views.Page();
// here you are sending {template:true} to '/products' in your server
window.app.view.collection.fetch( { data : { template : true } } );
});
Collections.Products=Backbone.Collection.extend({
url:“/products”,
解析:函数(响应){
//
//您应该从服务器返回JSON,并且对象必须类似于smth
//{模板:“产品模板””,数据:productsInJSON}
//
if(response.template&&response.data){
this.trigger('template',response.template);
返回响应数据;
}否则{
返回响应;
}
}
});
Views.Page=Backbone.View.extend({
初始化:函数(){
_.绑定(此“呈现”);
var self=这个;
this.collection=new Collections.Products();
this.collection.on('template',函数(template){
自渲染(模板);
});
},
渲染:函数(模板){
$(“div#page”).html(模板);
}
});
$(函数(){
window.app={};
window.app.view=新视图.Page();
//您正在将{template:true}发送到服务器中的“/products”
window.app.view.collection.fetch({data:{template:true});
});
如果您使用的是socket.io,那么应该为您的请求创建一个新的Backbone.sync方法
它有点脱离了主干哲学和集成的GET、PUT、POST、DELETE方法,因此会有很多编码
您可以为没有收集数据的未登录用户发送模板。谢谢您的回答。我会尝试使用类似的东西。我已经有了一个backbone.sync方法的替代品。有一个浮动在socket.io上运行良好,但它确实需要一些工作。