Javascript 我的扩展观测值是;删除“;调用ko.mapping.fromJS后

Javascript 我的扩展观测值是;删除“;调用ko.mapping.fromJS后,javascript,knockout.js,mapping,Javascript,Knockout.js,Mapping,我使用以下扩展器扩展了一个可观察的对象: ko.extenders.e2mElementName = function (target, options) { var result = ko.dependentObservable({ read: target, write: function (newValue) { var current = target.peek(); if (newValue !=

我使用以下扩展器扩展了一个可观察的对象:

ko.extenders.e2mElementName = function (target, options) {

    var result = ko.dependentObservable({
        read: target,
        write: function (newValue) {
            var current = target.peek();
            if (newValue != current) {

                newValue = newValue.replace(/[^0-9A-Za-z_]/g, "").replace(" ", "_");

                //check if name already exists
                if (!document._editor.elementNames)
                    document._editor.elementNames = [];

                if ($.inArray(newValue, document._editor.elementNames)) {
                    alert("The name '" + newValue + "' was already assigned to an element on this page");
                    target.notifySubscribers(current)
                } else {
                    document._editor.elementNames.remove(current);
                    document._editor.elementNames.push(newValue);
                    target(newValue);
                }

            }
        }
    }).extend({ notify: 'always' });

    //result(target());

    return result;
};
当我在构建时扩展可观测时,一切都很好,在我的对象构建中,我有:

this.Name = ko.observable("").extend({ e2mElementName: true });
但是在我调用mapping.fromJs之后,我的observable变为一个字符串,例如:“我的名字”

如果我移除扩展器,一切都会正常工作,并且我可以观察到缠绕字符串的情况


我做错了什么

您可以在调用ko.mapping.fromJS后添加扩展器

var applyMapping = function(rawData) {
  ko.mapping.fromJS(rawData, {}, this);
  this.name = this.name.extend({e2ElementName: true});
}
或者,您也可以使用映射插件选项进行此操作

var mappingOptions = {
  // customize the creation of the name property
  name: {
    create: function(data) {
        return ko.observable(data.name).extend( {e2ElementName: true} );
    }
  }
};

ko.mapping.fromJS(data, mappingOptions, this));
var mappingOptions = {
  // customize the creation of the name property
  name: {
    create: function(data) {
        return ko.observable(data.name).extend( {e2ElementName: true} );
    }
  }
};

ko.mapping.fromJS(data, mappingOptions, this));