dojo商店中的每个对象都需要具有相同的结构吗?

时间:2016-06-22 19:28:22

标签: dojo

例如,请参阅以下

require(["dojo/store/Memory",
"dojo/ready"],

function (Memory, ready) {
ready(function () {

//Creating array of data set
 var employees = [{
 name: "Krishna",
 topic: "Sales"
 }, {
 name: "Mohhamad",
 topic: "Sales"
 }, {
 name: "Sanaulla",
 topic: "Marketing"
 }, {
 name: "Raja",
 topic: "Marketing"
 }];

//Creating object store from the array
 var employeeStore = new dojo.store.Memory({
 data: employees,
 idProperty: "name"
 });

//Adding new data to the object store directly
 employeeStore.add({
 name: "Manisha",
 topic: "Advertising"
 });

然后我可以使用以下项目将员工添加到商店吗? (在这种情况下,员工有一个名为salary的新属性,在第一次创建商店时不存在)

//Adding new data to the object store directly
 employeeStore.add({
 name: "Manisha",
 topic: "Advertising",
 salary: "5"
 });

当我创建Memory Store时,商店中的每个对象是否都需要遵循在data属性上设置的原始对象结构?

2 个答案:

答案 0 :(得分:1)

您可以使用任何"结构/属性添加对象"在记忆库中。

下面和示例,如果您检查并查看商店的data属性,则可以看到所有正在添加的对象。

当使用从商店检索对象时,您需要注意对象的不同结构。

实施例: https://jsfiddle.net/6zygkhnf/

    require(['dojo/store/Memory'], function(Memory) {
  //Creating array of data set
  var employees = [{
    name: "Krishna",
    topic: "Sales"
  }, {
    name: "Mohhamad",
    topic: "Sales"
  }, {
    name: "Sanaulla",
    topic: "Marketing"
  }, {
    name: "Raja",
    topic: "Marketing"
  }];

  //Creating object store from the array
  var employeeStore = new dojo.store.Memory({
    data: employees,
    idProperty: "name"
  });

  //Adding new data to the object store directly
  employeeStore.add({
    name: "Manisha",
    topic: "Advertising"
  });
  employeeStore.add({
    name: "Manisha2",
    topic: "Advertising2",
    salary: "5"
  });
});

答案 1 :(得分:1)

对于添加了不同结构的新对象会发生什么,如果它没有在创建存储时指定的idProperty,则idProperty将自动添加到新对象。所有其他属性都无关紧要,它们可能因对象而异。即使新对象在添加到商店之前没有它,商店中的所有对象都将具有idProperty。

实施例

var employees = [{
    name: "Krishna",
    topic: "Sales"
}, {
    name: "Mohhamad",
    topic: "Sales"
}];

var testStore = new Memory({
    data: employees,
    idProperty: "name"
});

//Add a new employee object
testStore.add({ name: "blah", topic: "test1" });

//Add a new object with different properties
testStore.add({ something: "s1", other: "o1" });

商店将包含以下内容,请参阅最后一个对象具有不同的属性且没有name属性,但仍然添加了name属性。

enter image description here