[英]Test a Backbone.js View
我目前正在使用Jasmine測試主干視圖,但遇到了一些麻煩。 我試圖將視圖與所有其他元素(實例化的其他視圖,集合)隔離開來,但這幾乎是不可能的。
initialize: function(options) {
if(options.return) {return;}
var view = this;
var name = options.name;
var localizedElements = app.helpers.Locale.l().modules.case[name];
var swap, notification;
this.name = name.capitalizeFirstLetter();
this.collection.on('sort', this.refreshGui, this);
return this.render('/case/' + name + '/' + this.name + 'Box.txt', localizedElements, this.$el).done(function() {
new app.views.Buttons({el: view.$el.find('.Buttons')});
_.each(view.collection.models, function(model) {
new app.views['Folded' + this.name]({model: model, el: this.$('table')});
}, view);
if(!view.collection.findWhere({isPreferred: true}) || !view.collection.findWhere({isPrescribedForms: true})) {
if(!view.collection.findWhere({isPreferred: true})) {
swap = {entity: 'address', preferenceType: 'preferred'};
notification = app.helpers.Locale.l().generic.warningMessages.missingPreference.swap(swap);
var preferredNotification = [notification];
app.helpers.Notification.addNotifications('warnings', {missingPreferred: preferredNotification});
}
if(!view.collection.findWhere({isPrescribedForms: true})) {
swap = {entity: 'address', preferenceType: 'prescribed forms'};
notification = app.helpers.Locale.l().generic.warningMessages.missingPreference.swap(swap);
var prescribedFormsNotification = [notification];
app.helpers.Notification.addNotifications('warnings', {missingPrescribedForms: prescribedFormsNotification});
}
}
});
},
例如,在有兩個“ if”的地方,視圖正在與集合和一個助手對話:“ Notification Helper”。 如果我嘲笑了集合和通知助手,我應該如何測試這部分代碼? 我的意思是我正在測試VIEW,但是現在看來我必須在我的視圖中測試應用程序的其他元素...
我正在嘗試將視圖與所有其他元素隔離
我不確定這是否對您有幫助,但是我創建了自己的策略來解決此問題。
骨干網的問題通常確實是,視圖對象的功能變得雜亂無章。
就個人而言,我喜歡我的視圖來處理DOM交互,偵聽DOM事件。
但是,為了執行與后端的業務邏輯/交互,我更喜歡將此功能委托給其他“外部”對象。
另一方面,模型可以“處理”基本數據驗證,但無非是與應用程序中的服務器進行RESTful交互。
我如何解決該問題的方法是實例化自定義Javascript(“控制器”)對象,這些對象充當視圖和模型之間的中介。
這個對象不過是一個看起來像這樣的對象:
var Some_controller = function(options){
this.makeView();
};
Some_controller.prototype.makeView = function(){
var someView = new Some_view({'controller': this});
someView.render(); //Render, but can also take care of proper view cleanup to avoid zombie objects
};
Some_controller.prototype.getModel = function(){
var someModel = new Some_model();
var promise = model.fetch();
return promise; //Promise be called from the view, because the controller is passed via the options, when the view is instantiated.
};
好吧,這就是我嘗試保持觀點清潔的方式。
以我的經驗,很容易立即找到所有內容。 並且請注意,您還可以使用輔助對象來隔離更具體的業務功能。
不知道是否有人對此有更好的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.