我正在迭代一组可观察数据,但其中一些数据被交给了一个 javascript 函数来创建一个标签云。该站点的早期版本使用 ajax 和回调按预期工作:获取数据、迭代集合、注入目标 DOM 对象,一切正常。
现在我已经“进化”到使用 Breeze,并且承诺,我有一个时间问题,我的标签云被创建了,但我相信我注入它太早了。我已经验证,如果我在 JQuery 中遇到断点并检查 DOM,则这些元素尚不可用。在处理 w/promises 时如何调用 javascript 方法来操作 DOM?
define(['services/datacontext', 'durandal/plugins/router', 'durandal/system', 'durandal/app', 'services/logger', 'services/dataService'],
function (datacontext, router, system, app, logger, dataService) {
var member = ko.observable();
var positions = ko.observableArray();
var tags = ko.observableArray();
//#region Internal Methods
function activate(routeData) {
logger.log('Summary View Activated called', null, 'summary', true);
var id = parseInt(routeData.id);
datacontext.getMemberById(id, member);
datacontext.getPositions(id, positions).then(populateGraphics);
initLookups();
logger.log('Summary View Activate completed', null, 'summary', true);
return ;
}
var initLookups = function () {
salutations(datacontext.lookups.salutations);
};
var populateGraphics = function (pos) {
logger.log('populateGraphics called', null, 'home', true);
/// changed code that corrects issue based on suggestions
var n = $(".positionTagCloud").length;
if (n == 0) {
setTimeout(function () {
populateGraphics();
}, 500);
}
// end changes
for (var j = 0; j < positions().length; j++) {
var target;
var fill = d3.scale.category20();
var cloud = function (wordList, targetName) {
target = targetName;
d3.layout.cloud().size([540, 200])
.words(wordList.map(function (d) { return { text: d.name(), size: d.weight() * 1 }; }))
.rotate(function () { return ~ ~(Math.random() * 2) * 11; })
.font("Impact")
.fontSize(function (d) { return d.size; })
.on("end", draw)
.start();
};
function draw(words) {
d3.select(target).append("svg")
.attr("width", 540)
.attr("height", 200)
.attr("id", "canvas")
.attr("class", "cloudCanvas")
.append("g")
.attr("transform", "translate(250,100)")
.selectAll("text")
.data(words)
.enter().append("text")
.style("font-size", function (d) { return d.size + "px"; })
.style("font-family", "Impact")
.style("fill", function (d, i) { return fill(i); })
.attr("text-anchor", "middle")
.attr("transform", function (d) {
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
})
.text(function (d) { return d.text; });
$(target).append('hhh');
}
cloud(positions()[j].tags(), "#positionTagCloud" + positions()[j].id());
};
};
//#endregion
var vm = {
activate: activate,
cancel: cancel,
toggleProfileUpload: toggleProfileUpload,
title: 'Summary'
};
return vm;
});