Knockout自定义绑定模型没有得到更新

时间:2015-12-28 06:53:43

标签: knockout.js

最近我们出于某种原因将淘汰赛版本从2.1升级到3.4。下面的代码抛出一个错误,因为“modelValue不是一个函数”。在3.4。相同的代码块在2.1中工作正常。请帮我理解这个问题。

JAVASCRIPT:

init: function(element, valueAccessor) {
    var $el = $(element);

    // set a default if-empty value if none is provided
    if (typeof($el.data('if-empty')) === 'undefined') {
        $el.data('if-empty', 0);
    }
    else {
        $el.data('if-empty', parseInt($el.data('if-empty')));
    }

    // set a blur handler on the element to set the model value
    //  need to use blur event instead of change event, since IE doesn't always
    //  trigger the change event when the text input is cleared
    $el.on('blur', function() {
        var $elem = $(this);
        var modelValue = valueAccessor();
        var prefix = ($el.attr("numberprefix") || '').toString().trim();
        var elemVal = $elem.val().replace(/[,]/g, '').replace(prefix, '').trim();

        // check for invalid number
        if (isNaN(elemVal)) {
            $elem.addClass('invalidInput');
            $elem.after('<span class="errorSpan"><br />Numeric Only</span>');
            return;
        }

        // clear the errors
        $elem.parent().find('.errorSpan').remove();
        $elem.removeClass('invalidInput');

        // get the new value
        var newValue = (elemVal.length == 0)
            ? $elem.data('if-empty')
            : parseInt(elemVal);

        // set the new model value
        modelValue(newValue);

    });
},
update: function(element, valueAccessor) {
    var $elem = $(element);
    var updatedVal = ko.utils.unwrapObservable(valueAccessor());
    var prefix = ($elem.attr("numberprefix") || '').toString().trim();

    // set the value of the element
    //ko.utils.setTextContent(element, numberWithCommas(updatedVal, prefix));

    var value = numberWithCommas(updatedVal, prefix)
    if ((value === null) || (value === undefined))
        value = "";

    if ($elem.is(":input")) {
        $elem.val(value);
    }
    else {
        $elem.html(value);
    }
}

HTML:

<input type=text id="txtNetProfitLastLastYear" numberprefix='$' data-bind="numericFormatBinding: LastLastYear.NetProfitBeforeTaxes()"/>

0 个答案:

没有答案