如何生成观察块 [英] How to generate observe block
问题描述
我想像这样生成观察块:
I want to generate the observe block like so:
created: function () {
var viewData = {
type: 'Pikachu',
name: 'Gary'
};
// iterate over view data
for (prop in viewData) {
//set the property
this[prop] = viewData[prop];
var handlerName = 'update' + prop
// set add the property to the observe block
this.observe[prop] = handlerName;
// set the handler
this[handlerName] = function (valueWas, valueIs) {
console.log('you have changed ' + prop + ' to ' valueIs);
};
}
},
这可能吗?
这对我来说完全没有反应,没有错误,但是没有调用处理程序.
This is being completely unresponsive for me, no errors, but the handler isn't being called.
推荐答案
您缺少一些奥秘.在最终确定原型之前,polymer-element
代码将observe
映射分解为并行数组,作为(非常烦人的)速度优化.
You are missing some arcana. Before finalizing the prototype the polymer-element
code explodes the observe
map into parallel arrays as a (highly annoying) speed optimization.
您可以通过以下方式重新优化实例:
You can re-optimize your instance by calling:
this.element.optimizePropertyMaps(this);
this.element
指的是定义当前元素类型的polymer-element
(首先,众所周知element
是此属性的坏名).
Where this.element
refers to the polymer-element
that defined the current element type (fwiw, it's known that element
is a bad name for this property).
这里是一个例子:
http://jsbin.com/tahixumu/4/edit
出于性能考虑,Polymer认为观察者和其他特殊列表是共享原型的功能.由于您的动态数据大概是每个实例的 ,因此,为了进行适当的测试,我不得不使您的示例更加复杂.
Also for performance, Polymer considers the observers and other special lists to be features of a shared prototype. Since your dynamic data is presumably per-instance I had to make your example more complicated for a proper test.
请注意,由于颠覆了Polymer对每个原型的期望,可能还会出现其他并发症.
Keep an eye out, there may be other complications due to subverting Polymer's per-prototype expectations.
这篇关于如何生成观察块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!