如何构造backbone.js所以它返回模板+数据和(基于登录的重新路由)

时间:2012-03-23 13:01:14

标签: backbone.js

我正在构建一个小型应用程序,它在客户端使用backbone.js,在服务器端使用node.js / socket.io,并且连接仅通过websockets进行。

现在,如果我想立即获取模板和数据,我将如何进行设置。

  1. 我在路由器中执行fetch(),获取数据和模板。有了这个,我构建了我的观点 - >收藏 - >模型。

  2. 我在视图中执行fetch()。 (也许在初始化中)

  3. ===

    我想用以下内容扩展此问题。

    假设用户浏览http://mysite.com/products并且用户尚未登录,则不允许他查看该页面。他必须改为/login

    问题是我只能在服务器上验证这一点,因此无论用户是否登录,服务器都必须发回正确的数据,而backbone.js必须处理此问题。

    总结
    我向服务器取一个将发送回数据+模板html。

    Backbone.js必须使用数据

    呈现模板 当服务器发回标志时,

    或重新路由(Backbone.history.navigate('login', {trigger: true}))。

1 个答案:

答案 0 :(得分:2)

您可以在Backbone集合中使用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 } } );

});

如果您使用的是socket.io,则应为您的请求创建一个新的Backbone.sync方法。

它有点脱离Backbone哲学和集成的GET,PUT,POST,DELETE方法,所以会有很多编码。

您可以在没有数据的用户中发送未登记的模板。