我想将knockout属性绑定到svg文本元素的长度,以便每次更改文本时都设置它。我从这样的事情开始:
ko.bindingHandlers.length = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
var width = element.getComputedTextLength();
valueAccessor()(width);
element.onchange = function() {
var newWidth = element.getComputedTextLength();
valueAccessor()(newWidth);
};
}
};
和svg元素
<text data-bind="text: text, length: labelLength" x="0" y="0" fill="black">Hello World</text>
jsfiddle在这里http://jsfiddle.net/9vWhD/
有关最佳方法的想法吗?
答案 0 :(得分:0)
如果要在文本更改时设置元素的宽度,可以使用计算的observable(小提琴:http://jsfiddle.net/9vWhD/3/):
var model = function(){
this.text = ko.observable("Hello World");
this.labelLength = ko.computed(function(){
return this.text().length * 10;
});
this.changeText = function(){
this.text("This is some much longer text");
}
}
或者您想在设置文本后获取文本元素的宽度?如果是这种情况,您可以像这样更改自定义绑定(小提琴:http://jsfiddle.net/9vWhD/6/):
ko.bindingHandlers.textSetLength = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
},
update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
$(element).text(valueAccessor()());
var width = $(element)[0].getBoundingClientRect().width;
this.labelLength(width);
}
};