Quantcast
Channel: JavaScriptMVC Forum
Viewing all articles
Browse latest Browse all 3491

can.Component: dynamic attribute values binding to scope

$
0
0
Hello.

I have a sample component, which wraps <img> and hides it if provided URL is broken:

    define(['can/component'], function(Component) {
    
        return Component.extend({
            tag: 'smart-image',
            template: '<img src="{{src}}" alt="{{alt}}">',
            scope: {
                src: '@',
                alt: '@',
                checkImage: function () {
                    this.image.src = this.src;
                }
            },
            events: {
                init: function () {
                    var me = this;
                    var image = this.scope.image = new Image();
                    image.onload = function () {
                        me.element.css('visibility', 'visible');
                    };
                    image.onerror = function () {
                        me.element.css('visibility', 'hidden');
                    };
                    this.scope.checkImage();
                },
                '{scope} src': function () {
                    this.scope.checkImage();
                }
            }
        });
    });

It works fine for for static URLs (like <smart-image src="path/to/image.png"></smart-image>). But does not work correct if URL is bound to can.Map (like <smart-image src="{{player.photoUrl}}"></smart-image>). In the second case it only works if player.photoUrl already defined at the moment of component instantiation. If not - src attribute value on wrapped <img> stays empty. Component also can't handle dynamic change of the player.photoUrl value.

Could you suggest how to work it around or implement in a proper way? Or it's a CanJS issue?

Thanks

Viewing all articles
Browse latest Browse all 3491

Trending Articles