Backbone Marionette - 如何使用fetch方法在视图模板中获取返回数据

时间:2014-09-16 07:34:01

标签: jquery backbone.js marionette fetch

在我的应用中,我正在使用passport - 在登录时进行身份验证,一旦登录成功,我将重定向到主页,如下所示:

router.post('/login', passport.authenticate('login', {
        successRedirect: '/#home',
        failureRedirect: '/',
        failureFlash : true
    }));

我被重定向到home页面。重定向到主页我从路由器传递这样的用户信息:

router.get('/#home', isAuthenticated, function(req, res){
        res.render('index', { user: req.user });
});

现在我想收到用户详细信息..因为我使用的模型获取数据:

define(['backbone'], function(Backbone){
    "use strict";
    socialApp = window.socialApp || {};

    socialApp.homeModel = Backbone.Model.extend({
        url:'/home',
        defaults:{
            name:"from home"
        },
        initialize:function(){
            console.log('from home Model'); //works!
        }
    });

    return socialApp.homeModel;
});

在视图中,我从模型中获取数据,如:

define([
    'jquery',
    'underscore',
    'backbone',
    'marionette',
    'hbs!scripts/templates/home/homeTemp'],
    function ($,_,Backbone, Marionette, homeTemp) {
        "use strict";
        socialApp = window.socialApp || {};

        socialApp.homeView = Backbone.Marionette.ItemView.extend({
            template:homeTemp(),
            initialize:function () {
                console.log('view init');
                this.model.fetch({
                    success: function (data) {
                        console.log(data); // but nothing happening!
                    }
                });
            }
        });

        return socialApp.homeView;
});

任何人帮我辨别我在这里做错了什么?并且任何人都可以帮我获取数据吗?

更新

router.get('/home', isAuthenticated, function(req, res){
        res.render('index');
        console.log('req.user is ' + req.user) // i am getting correct out put here. how to send to mode.fetch..?
        return { user: req.user }; // after redering generic html(index) returning the object.
    });

2 个答案:

答案 0 :(得分:0)

我更新了我的路线以发送这样的数据:它适用于我

router.get('/home', isAuthenticated, function(req, res){
        return res.send(req.user);
    });

任何方式,感谢所有..

答案 1 :(得分:0)

我认为你根本不使用控制器?我通常在我的控制器中处理它(在我的路由器将它们路由到这里之后)。

@SampleApp.module "PostsApp.List", (List, App, Backbone, Marionette, $, _) ->

  class List.Controller extends App.Controllers.Application

    initialize: ->
        posts = App.request "post:entities"

        App.execute "when:fetched", posts, =>
            @layout = @getLayoutView()

            @listenTo @layout, "show", =>
          @postsRegion posts

        @show @layout

获取时基本上只是等待获取实体,然后运行代码块 - 即延迟加载。