2014-03-03 39 views
1

登錄後,用戶被重定向到另一個頁面。因此,響應登錄模型從服務器獲取,它嘗試設置爲另一個模型。
第二個模型從第一個模型中正確設置。但當它到達另一個頁面的視圖時,它將變爲空。
模式骨幹:設置服務器從一個模型到另一個模型的響應

var LoginModel = Backbone.Model.extend({ 
    url:'http://localhost:3000/login', 

    defaults: { 
     email:"", 
     password:"" 
    }, 
    parse: function(resp) { 
     console.log('Model: Got the response back'); 
     return resp; 
    }, 
    login: function() { 
     console.log('Model: Login function:'+JSON.stringify(this)); 
     this.save(
      {}, { 
       success: function(resp) { 
        console.log('success'+JSON.stringify(resp)); 
        dashboardModel.set(resp.result); 
        window.location = 'templates/dashboard.html' 
       }, 
       error: function(error) { 
        console.log('error: '+JSON.stringify(error)); 
       } 
      }); 
    }, 
    redirect: function() { 
     console.log('inside redirect method'); 
    } 
}); 
var loginModel = new LoginModel(); 

var DashboardModel = Backbone.Model.extend({ 
    defaults: { 
     campaignName:"", 
     orderedAndGoal:"", 
     status:"", 
     endDate:"", 
    }, 
    parse: function(resp) { 
     console.log('Model: Got the response back'); 
     return resp; 
    } 
}); 
var dashboardModel = new DashboardModel(); 

查看

var DashboardView = Backbone.View.extend({ 
    template:_.template('<div>'+ 
         '<h3><%= campaignName %></h3>'+ 
         '<span><%= orderedAndGoal %>, </span>'+ 
         '<span><%= status %>, </span>'+ 
         '<span><%= endDate %>, </span>'+ 
         '</div>'), 
    initialize: function() { 
     this.model.on('change', this.render, this); 
    }, 
    render: function() { 
     console.log('what happens here') 
     var attributes = this.model.toJSON(); 
     this.$el.html(this.template(attributes)); 
    }, 
}); 
var dashboardView = new DashboardView({model: dashboardModel}); 
dashboardView.render(); 
$(".container").append(dashboardView.el); 

回答

0

你從字面上導航到另一個HTML頁面window.location = ...。這不會奏效。當瀏覽器導航到另一個頁面時,所有正在運行的代碼以及它們設置的任何變量都會被吹走。 Backbone主要是關於創建「單頁面應用程序(SPA)」,其中瀏覽器僅加載1個頁面,然後在運行時動態更改DOM。看看Backbone.Router作爲理解這一點的出發點。你會調用方法該路由器上的用戶轉移到另一個「說法」,而不是觸摸window.location

修復了,你的代碼應該工作:)