按名称获取实体属性值 - 在客户端上

时间:2013-11-07 15:02:08

标签: breeze

假设我有一个实体Person和字符串定义属性的“路径” - 让我们说'Address.Country'。是否有一个函数可以让我访问可观察的持有国?

1 个答案:

答案 0 :(得分:1)

您可以从getProperty和setProperty方法开始。

var address = myEntity.getProperty("Address");
var country = address.getProperty("Country");

然后你可以使用

function getPropertyPathValue(obj, propertyPath) {
    var properties;
    if (Array.isArray(propertyPath)) {
        properties = propertyPath;
    } else {
        properties = propertyPath.split(".");
    }
    if (properties.length === 1) {
        return obj.getProperty(propertyPath);
    } else {
        var nextValue = obj;
        for (var i = 0; i < properties.length; i++) {
            nextValue = nextValue.getProperty(properties[i]);
            // == in next line is deliberate - checks for undefined or null.
            if (nextValue == null) {
               break;
            }
        }
        return nextValue;
    }
}

'propertyPath'参数可以是字符串数组或'。'分隔路径

   var country = getPropertyPath(myEntity, "Address.Country");

   var country = getPropertyPath(myEntity, ["Address", "Country"]);