2015-04-23 255 views
1

我需要測試一個JavaScript項目。這裏描述了幾個模塊,但是當我嘗試加載它們時出錯了。如何正確使用RequireJS?

define([ 
    'core/BaseModel' 
], 

function (BaseModel) { 
    var MessageModel = BaseModel.extend({ 
    defaults: { 
     messageType: "Advertisment", 
     receiver: "me", 
     title: "Title", 
     heading_1: "Heading1", 
     heading_2: "Heading2" 
    }, 

    url: function() { 
     var base = this.apipath + '/companies/'; 
     if (this.isNew()) return base; 
     return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + this.id; 
    } 
    }); 

    return MessageModel; 
}); 

要加載我這樣做的模塊:

var message; 
beforeAll(function(done){ 
    require(['../../../public/js/app/models/Message'], function(Message){ 
     message = Message; 
     done(); 
    }); 
}); 

現在消息不是未定義的,但是當我測試,如果message.defaults或message.url定義此失敗。那裏有什麼問題?

回答

0

鑑於../../../public/js/app/models/Message對應MessageModel,你想要做的是:

var Message = require('../../../public/js/app/models/Message');

和創建一個新的實例:var m = new Message();

希望這會有所幫助。

+0

sry那不是我的目的。我編輯了上面的代碼。它應該說'Message'而不是'User'。但這並沒有解決問題。 – Garrarufa

+0

在Java中,我會說我想創建消息的一個實例。 – Garrarufa

+0

編輯我的答案來演示如何創建一個實例。 –

-1

我找到了一個適用於這個確切例子的解決方案。取而代之的

message = Message; 

我寫

message = new Message(); 

但我用不同的模塊完全相同,只給出了一個超時錯誤,並不斷未定義:

var router; 

beforeAll(function(done){ 
    require(['../../../public/js/app/routers/DesktopRouter'], function(Router){ 
     router = new Router(); 
     done(); 
    }); 
}); 

它的定義是:

define(["jquery", "underscore", "backbone", "core/BaseRouter", "models/Session", "i18n!locales", 

    "views/NavbarView", 
    "views/LoginView", 
    'views/SidebarView', 
    'views/FooterView', 
    'views/VehicleSidebarView', 
    "views/DashboardView", 
    "views/CompaniesView", 
    "views/WorkshopsView", 
    "views/VehiclesView", 
    "views/UsersView", 
    "views/AddVehicleView", 
    "views/VehicleTripsView", 
    "views/VehicleDataView", 
    "views/VehicleServiceView", 
    "views/VehicleErrorsView", 
    "views/MessageInboxView", 
    "views/AddUserView", 
    "views/EditUserView", 
    "views/EditProfileView", 
    "views/AppDownloadView", 
    "views/BlockBrowserView" 
], 

function($, _, Backbone, BaseRouter, Session, i18n, 

     NavbarView, 
     LoginView, 
     SideBarView, 
     FooterView, 
     VehicleSidebarView, 
     DashboardView, 
     CompaniesView, 
     WorkshopsView, 
     VehiclesView, 
     UsersView, 
     AddVehicleView, 
     VehicleTripsView, 
     VehicleDataView, 
     VehicleServiceView, 
     VehicleErrorsView, 
     MessageInboxView, 
     AddUserView, 
     EditUserView, 
     EditProfileView, 
     AppDownloadView, 
     BlockBrowserView 
) { 

var DesktopRouter = BaseRouter.extend({ 

    initialize: function() { 
..... 
+0

請不要在答案中發佈進一步的問題。 – kryger