Breeze использует ViewModel хостинг-инфраструктуры MVVM. Это, как правило, хорошее решение. Кроме того, отслеживание изменений для сущностей является фундаментальной концепцией breeze.js (то же самое для Entity Framework). Легкая задача отслеживать изменения, если среда MVVM использует Observables с реальными getter и seters (например, Knockout). AngularJS с другой стороны работает с обычными объектами JavaScript. Это затрудняет отслеживание изменений. Единственными двумя надежными способами являются ES5-свойства (простые, но не поддерживаемые IE8) или очень глубокая интеграция в цикле $ digest. Команда бриза взяла первый выбор - как жаль проектов, которые должны поддерживать IE8!
Ok, let's analyze the root cause of the problem: change tracking
Вам действительно нужна эта функция? По крайней мере, в нашем проекте мы решили использовать breeze.js/OData для чтения и для более «спокойного» подхода, когда дело доходит до написания. Если вам не нужны эти дополнительные функции, следующий сценарий должен решить проблему:
/********************************************************
* A replacement for the "backingStore" modelLibrary
*
* This is a bare version of the original backingStore,
* without ANY change tracking - that's why it will work in IE8!
* (Object.defineProperty not required any more)
*
* This adapter is a "drop in" replacement for the "backingStore" adapter in Breeze core.
* It has the same adapter name so it will silently replace the original "backingStore" adapter
* when you load this script AFTER the breeze library.
* WARNING: For obvious reasons a lot of breeze magic will be lost!
*
* Author: Johannes Hoppe/haushoppe-its.de
*
* Copyright 2014 IdeaBlade, Inc. All Rights Reserved.
* Use, reproduction, distribution, and modification of this code is subject to the terms and
* conditions of the IdeaBlade Breeze license, available at http://www.breezejs.com/license
******************************************************/
(function (definition, window) {
if (window.breeze) {
definition(window.breeze);
} else if (typeof require === "function" && typeof exports === "object" && typeof module === "object") {
//CommonJS or Node
var b = require('breeze');
definition(b);
} else if (typeof define === "function" && define["amd"] && !window.breeze) {
//Requirejs/AMD
define(['breeze'], definition);
} else {
throw new Error("Can't find breeze");
}
}(function (breeze) {
"use strict";
var core = breeze.core;
var ctor = function() {
this.name = "backingStore";
this.A_BIG_FAT_WARNING = "This is a bare version of the backingStore! Change tracking won't work!";
};
var protoFn = ctor.prototype;
protoFn.initialize = function() {
};
protoFn.getTrackablePropertyNames = function (entity) {
var names = [];
for (var p in entity) {
if (p === "entityType") continue;
if (p === "_$typeName") continue;
var val = entity[p];
if (!core.isFunction(val)) {
names.push(p);
}
}
return names;
};
protoFn.initializeEntityPrototype = function (proto) {
proto.getProperty = function (propertyName) {
return this[propertyName];
};
proto.setProperty = function (propertyName, value) {
this[propertyName] = value;
return this;
};
};
//This method is called when an EntityAspect is first created - this will occur as part of the entityType.createEntity call.
//which can be called either directly or via standard query materialization
//entity is either an entity or a complexObject
protoFn.startTracking = function (entity, proto) {
//assign default values to the entity
var stype = entity.entityType || entity.complexType;
stype.getProperties().forEach(function (prop) {
var propName = prop.name;
var val = entity[propName];
if (prop.isDataProperty) {
if (prop.isComplexProperty) {
if (prop.isScalar) {
val = prop.dataType._createInstanceCore(entity, prop);
} else {
val = breeze.makeComplexArray([], entity, prop);
}
} else if (!prop.isScalar) {
val = breeze.makePrimitiveArray([], entity, prop);
} else if (val === undefined) {
val = prop.defaultValue;
}
} else if (prop.isNavigationProperty) {
if (val !== undefined) {
throw new Error("Cannot assign a navigation property in an entity ctor.: " + prop.Name);
}
if (prop.isScalar) {
//TODO: change this to nullstob later.
val = null;
} else {
val = breeze.makeRelationArray([], entity, prop);
}
} else {
throw new Error("unknown property: " + propName);
}
entity[propName] = val;
});
};
breeze.config.registerAdapter("modelLibrary", ctor);
}, this));
Download at: https://gist.github.com/JohannesHoppe/72d7916aeb08897bd256
Это голая версия оригинальной базы backingStore, без каких-либо изменений отслеживания - вот почему она будет работать в IE8! (Object.defineProperty больше не требуется) Этот адаптер является «заменой» для замены адаптера «backingStore» в ядре Breeze. Он имеет одно и то же имя адаптера, поэтому он будет молча заменить оригинальный адаптер backingStore, когда вы загружаете скрипт ПОСЛЕ БИСТОВОЙ библиотеки.
Here is a demo to proof the functionality:
http://jsfiddle.net/Johannes_Hoppe/bcav9hzL/5/
JsFiddle does not support IE8, please use this direct link:
http://jsfiddle.net/Johannes_Hoppe/bcav9hzL/5/embedded/result/
Ура!