【问题标题】:SAPUI5 - property scopeSAPUI5 - 属性范围
【发布时间】:2014-07-02 17:48:48
【问题描述】:

我有两个控件,一个从 Control 扩展而来,一个从我的自定义控件扩展而来。

控件有一个数组属性,我希望每个实例都是唯一的:

/* parent control */
sap.ui.core.Control.extend("foo.MyControl", {
    metadata: {
        properties: {
            name: { type: 'string' },
            myArray: { type: 'array', defaultValue: [] }
        }
    },
    renderer: {
        render: function( oRenderManager, oControl ) {
            oRenderManager.write('<div>My name is: ' + oControl.getName() + '</div>');
        }
    }
});

/* child control */
foo.MyControl.extend("foo.MyChildControl", {
    renderer: {
        render: foo.MyControl.prototype.render
    }
});

然后我创建它们的实例并将它们放在 dom 中:

/* create and place instances */
var oMyControl = new foo.MyControl({
        name: 'parent control'
    }),
    oMyChildControl = new foo.MyChildControl({
        name: 'child control'
    });
oMyControl.placeAt('uiArea');
oMyChildControl.placeAt('uiArea');

为什么两个数组实例相等?

alert(oMyControl.getMyArray() === oMyChildControl.getMyArray()); // true

我希望每个实例都有自己的数组。

**

TL;DR 对于定义控件元数据,将数组属性声明为“object”类型

**

【问题讨论】:

  • 您的示例中可能缺少代码,因为它显示为 oMyControl.getMyArray() === [] && oMyChildControl.getMyArray() === [], ([] === [] ) 真的
  • 如果我填充 oMyControl.getMyArray() 它也会填充 oMyChildControl.getMyArray() 因为它们共享相同的引用,这是我感到困惑的。我希望他们有自己的数组实例。

标签: sapui5


【解决方案1】:

我在尝试运行您的代码时遇到异常

type: 'array' 不正确

JavaScript 中的 typeof 运算符为数组返回“对象”。

这对我有用

sap.ui.core.Control.extend("foo.MyControl", {
    metadata: {
        properties: {
            name: {
                type: 'string'
            },
            myArray: {
                type: 'object',
                defaultValue: []
            }
        }
    },
    renderer: {
        render: function(oRenderManager, oControl) {
            oRenderManager.write('<div>' + oControl.getMyArray().toString() + '</div>');
        }
    }
});

/* child control */
foo.MyControl.extend("foo.MyChildControl", {
    renderer: {
        render: foo.MyControl.prototype.render
    }
});

/* create and place instances */
var oMyControl = new foo.MyControl({
    name: 'parent control'
}).placeAt('content');

var oMyChildControl = new foo.MyChildControl({
        name: 'child control'
}).placeAt('content');

var aFruits = ["Banana", "Orange", "Apple", "Mango"];
var aColors = ["Red", "Blue", "Green"];
oMyControl.setMyArray(aFruits);
oMyChildControl.setMyArray(aColors);

【讨论】:

    猜你喜欢
    • 2014-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多