javascript - Durandal 撰写时的装订处理不正确

标签 javascript jquery knockout.js durandal durandal-navigation

Durandal 在附加 View 之前将 View 模型绑定(bind)到 View ,当您尝试使用 jquery 检查元素大小时,它总是返回 0。这是因为 jQuery 无法获取不可见或位于不可见容器中的元素的正确大小。

我的绑定(bind)处理程序,它将文本限制为一定行数,并将剩余文本替换为 ellipsis ,当 durandal 绑定(bind)页面时不起作用,但在第二次更新后,当元素可见时起作用

ko.bindingHandlers.ellipsis = {
    update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
        ko.bindingHandlers.text.update(element, valueAccessor);
        var lines = allBindings.get('lines');

        var $element = $(element);
        var lineHeight = 1.3;
        var heigth = lines * (+$element.css('font-size').substr(0, 2)) * lineHeight;

        while ($element.outerHeight() > heigth) {
            $element.text(replaceLast);
        }

        function replaceLast(index, text) {
            return text.replace(/\W*\s(\S)*$/, '...');
        }
    }
};

我在使用 jQuery.customSelect 时也遇到了这个问题通过绑定(bind)处理程序以及当我通过手动绑定(bind)回调使用它时

最佳答案

使用延迟绑定(bind)处理程序。 来自 Durandal docs ,

Sometimes your binding handler needs to work with an element only after it is attached to the DOM and when the entire composition of the view is complete. An example of this is any code that needs to measure the size of an HTML element. Durandal provides a way to register a knockout binding handler so that it does not execute until the composition is complete. To do this, use composition.addBindingHandler. One common use is in focusing elements. If you have an existing registered binding handler, you can change its execution time simply by doing this:

因此您的出价处理程序将变为以下内容:

composition.addBindingHandler('ellipsis', {
    update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
        ko.bindingHandlers.text.update(element, valueAccessor);
        var lines = allBindings.get('lines');

        var $element = $(element);
        var lineHeight = 1.3;
        var heigth = lines * (+$element.css('font-size').substr(0, 2)) * lineHeight;

        while ($element.outerHeight() > heigth) {
            $element.text(replaceLast);
        }

        function replaceLast(index, text) {
            return text.replace(/\W*\s(\S)*$/, '...');
        }
    }
});

关于javascript - Durandal 撰写时的装订处理不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21711356/

相关文章:

javascript - 我应该如何使用 jquery 填充嵌套元素?

jQuery 转移到另一个 DOM 节点后获取原始 $(this) ?

jquery - 在多个页面中使用 KnockoutJS

javascript - Knockout,为什么我的函数没有在 clickevent 上触发?

java - 在java中通过Google获取地址经度和纬度的最佳方法是什么

javascript - 无法使用 jquery 从 html 表中删除行

javascript - 在 Internet Explorer 中旋转时钟指针

jquery - val() 不会触发 jQuery 中的 change()

javascript - knockout : some observables binding but not visible in Safari

javascript - Jquery 获取没有父级的列表值