我对以下扩展器进行了扩展观察:
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;
};
当我在构造中扩展observable时,一切正常,在我的对象构造中我有:
this.Name = ko.observable("").extend({ e2mElementName: true });
但在我调用mapping.fromJs后,我的observable被改为字符串ex:" My Name" ...
ko.mapping.fromJS(rawData, mapping, this);
如果我删除扩展器一切正常,我有可观察的包裹字符串......
我做错了什么?答案 0 :(得分:6)
你可以在调用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));