Gary Ryan
Gary Ryan

Reputation: 754

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);
                };
            }
        },

Is this possible?

This is being completely unresponsive for me, no errors, but the handler isn't being called.

Upvotes: 0

Views: 98

Answers (1)

Scott Miles
Scott Miles

Reputation: 11027

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);

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).

Here is an example:

http://jsbin.com/tahixumu/4/edit

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.

Keep an eye out, there may be other complications due to subverting Polymer's per-prototype expectations.

Upvotes: 1

Related Questions