我正在尝试弄清楚如何使用自定义视图位置策略,我已阅读此页面上的文档http://durandaljs.com/documentation/Using-Composition/,但我并不完全了解策略功能应该是什么样的。
有人能给我一个快速的例子,说明这个函数的实现是什么样的,以及返回的承诺(即使是简单的函数)等等?
提前致谢, 加里
P.S。这是我的html中的代码:
<div>
<div data-bind="compose: {model: 'viewmodels/childRouter/first/simpleModel', strategy:
'viewmodels/childRouter/first/myCustomViewStrategy'}"></div> </div>
这是myCustomViewStrategy中的代码:
define(function () {
var myCustomViewStrategy = function () {
var deferred = $.Deferred();
deferred.done(function () { console.log('done'); return 'simpleModelView'; });
deferred.fail(function () { console.log('error'); });
setTimeout(function () { deferred.resolve('done'); }, 5000);
return deferred.promise();
};
return myCustomViewStrategy;
});
但是我收到了错误:
未捕获的TypeError:无法读取未定义的属性'display' - 这是在完成后已在控制台窗口中记录。
答案 0 :(得分:1)
好的,我通过以下方式创建自定义视图策略来解决这个问题:
define(['durandal/system', 'durandal/viewEngine'], function (system, viewEngine) {
var myCustomViewStrategy = function () {
return viewEngine.createView('views/childRouter/first/sModelView');
}
return myCustomViewStrategy;
});
答案 1 :(得分:1)
由于我发现文档有点缺乏撰写绑定的策略设置,因此检查了源代码的工作原理。总结一下:
compose绑定的策略设置由moduleId
指定的模块一个工作示例:
define(['durandal/system', 'durandal/viewEngine'], function (system, viewEngine) {
var strategy = function(settings){
var viewid = null;
if(settings.model){
// replaces model's module id's last segment ('/viewmodel') with '/view'
viewid = settings.model.__moduleId__.replace(/\/[^\/]*$/, '/view');
}
return viewEngine.createView(viewid);
};
return strategy;
});
杜兰达尔的消息来源:
// composition.js:485
for (var attrName in settings) {
if (ko.utils.arrayIndexOf(bindableSettings, attrName) != -1) {
/*
* strategy is unwrapped
*/
settings[attrName] = ko.utils.unwrapObservable(settings[attrName]);
} else {
settings[attrName] = settings[attrName];
}
}
// composition.js:523
if (system.isString(context.strategy)) {
/*
* strategy is loaded
*/
system.acquire(context.strategy).then(function (strategy) {
context.strategy = strategy;
composition.executeStrategy(context);
}).fail(function(err){
system.error('Failed to load view strategy (' + context.strategy + '). Details: ' + err.message);
});
} else {
this.executeStrategy(context);
}
// composition.js:501
executeStrategy: function (context) {
/*
* strategy is executed
* expected to be a promise
* which returns the view to be bound and inserted to the DOM
*/
context.strategy(context).then(function (child) {
composition.bindAndShow(child, context);
});
}