我是 javascript 和 Polymer 的初学者:我需要在我的自定义对象中使用原生的 polymer push 方法,但它返回给我的浏览器:
“未捕获的类型错误:无法读取未定义的属性‘长度’”
这是我的代码的简化版本:
<link rel='import' href='bower_components/polymer/polymer.html'>
<dom-module id='random-tag'>
<template>
<template is='dom-repeat' items='[[MyObject.getArray()]]'>
<div>
<h2>[[item.id]]</h2>
</div>
</template>
</template>
<script>
Polymer({
is: 'random-tag',
properties: {
MyObject: {
type: Object
}
},
MyObject2: function(){
var myArray = [];
var idMap = {};
this.getArray = function(){
return this.myArray
};
this.add = function(element){
//The problem is here: probably Polymer don't see 'myArray'
//in MyObject2 because the path is wrong
Polymer.Base.push('myArray', element)
idMap[element.id] = myArray.length
};
this.getIndex = function(id){
return idMap[id]
}
},
ready: function(){
this.MyObject = new this.MyObject2()
this.MyObject.add({id : 'thing1'})
console.log('thing1 has index: ' + this.MyObject.getIndex('thing1'))
}
});
</script>
</dom-module>
最佳答案
你需要从一个像
这样的 Polymer 元素开始<script>
Polymer({
is: 'random-tag',
properties: {
MyObject: {
type: Object
}
},
var self = this;
MyObject2: function(){
var myArray = [];
var idMap = {};
this.getArray = function(){
return this.myArray
};
this.add = function(element){
//The problem is here: probably Polymer don't see 'myArray'
//in MyObject2 because the path is wrong
self.push('myArray', element)
idMap[element.id] = myArray.length
};
this.getIndex = function(id){
return idMap[id]
}
},
ready: function(){
this.MyObject = new this.MyObject2()
this.MyObject.add({id : 'thing1'})
console.log('thing1 has index: ' + this.MyObject.getIndex('thing1'))
}
});
</script>
</dom-module>
未测试(本人不太懂JS,谨慎使用)
关于javascript - 在对象中使用 Polymer push 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37231637/