【发布时间】:2015-08-06 15:27:59
【问题描述】:
我正在学习 Backbone,并希望在模型中“模拟”.fetch() 调用的结果。我不想使用测试库或实际使用外部服务。
基本上我的模型中有一个设置,如果this.options.mock === true,则只需使用内部 JSON 对象作为获取的“结果”。否则,实际上是通过真正的 AJAX 请求访问 API。
但是,这似乎不起作用。当我点击实际 API(“真实”获取)时,我的视图成功地呈现了模型数据,但每当我尝试传递假数据时都不会。
有没有办法在 Backbone 中伪造 Fetch 响应,而不需要引入像 Sinon 这样的测试库?
这是完整的模型(至少是其中的相关部分)。基本上,模型获取数据,并将其格式化为模板。然后拥有该模型的视图将其渲染出来。
'use strict';
(function (app, $, Backbone) {
app.Models.contentModel = Backbone.Model.extend({
/**
* Initializes model. Fetches data from API.
* @param {Object} options Configuration settings.
*/
initialize: function (options) {
var that = this;
that.set({
'template': options.template,
'mock': options.mock || false
});
$.when(this.retrieveData()).then(function (data) {
that.formatDataForTemplate(data);
}, function () {
console.error('failed!');
});
},
retrieveData: function () {
var that = this, deferred = $.Deferred();
if (typeof fbs_settings !== 'undefined' && fbs_settings.preview === 'true') {
deferred.resolve(fbs_settings.data);
}
else if (that.get('mock')) {
console.info('in mock block');
var mock = {
'title': 'Test Title',
'description': 'test description',
'position': 1,
'byline': 'Author'
};
deferred.resolve(mock);
}
else {
// hit API like normal.
console.info('in ajax block');
that.fetch({
success: function (collection, response) {
deferred.resolve(response.promotedContent.contentPositions[0]);
},
error: function(collection, response) {
console.error('error: fetch failed for contentModel.');
deferred.resolve();
}
});
}
return deferred.promise();
},
/**
* Formats data on a per-template basis.
* @return {[type]} [description]
*/
formatDataForTemplate: function (data) {
if (this.get('template') === 'welcomead_default') {
this.set({
'title': data.title,
'description': data.description,
'byline': data.author
});
}
// trigger the data formatted event for the view to render.
this.trigger('dataFormatted');
}
});
})(window.app, window.jQuery, window.Backbone);
视图中的相关位(ContentView):
this.model = new app.Models.contentModel({template: this.templateName});
this.listenTo(this.model, 'dataFormatted', this.render);
数据设置太快以至于监听器还没设置好?
【问题讨论】:
-
您能否在 if-else 块周围包含更多代码?它在模型中的什么位置以及如何调用它?记住mcve。从您发布的代码中,其他人很难发现问题所在。
-
fetch()会触发一系列您无法通过这种方式导致的相关事件。你必须覆盖Backbone.sync -
@ivarni 我已将我的完整模型添加到原始帖子中。
-
是的.. 这与原始代码有很大不同 :) 我假设您在控制台中看到了
in mock block打印?对我来说,代码看起来不错,但我没有太多使用 jQuery Promise API 的经验。此外,在 this 稍微修改了代码的 jsbin 中,它似乎工作得很好。您基本上在初始化时触发了一个事件,因为您快捷地编写了代码,因此视图很可能尚未为该事件设置其侦听器。在解决模拟案例中的延迟之前尝试添加超时。 -
@Prefix 我可能在您输入时进行了编辑。使用
setTimeout。
标签: javascript ajax json backbone.js model