淘汰赛组成图像src

时间:2014-05-16 13:55:18

标签: javascript knockout.js foreach src

我有以下代码,并且无法为图像编写src。

问题在于访问src中的经度和纬度参数,因为上面我可以访问它们来打印它们。

<div data-bind='foreach: posts'>
            <div class="well">
                <div class="row">
                    <div class="col-xs-12 col-md-12"><h4><span data-bind='text: Name'></span></h4></div>
                </div>
                <div class="row">
                    <div class="col-xs-12 col-md-8">
                        <div class="row">
                            <div class="col-xs-12 col-md-2"><b>Address:</b></div>
                            <div class="col-xs-12 col-md-10"><span data-bind='text: Address'></span></div>
                        </div>
                    </div>
                    <div class="col-xs-12 col-md-4">
                        Longitude: <span data-bind='text: Longitude'></span> -  Latitude: <span data-bind='text: Latitude'></span>
                        <img data-bind="attr: {'src':  'http://maps.googleapis.com/maps/api/staticmap?center='+ Latitude+','+ Longitude+'&zoom=13&size=300x300&maptype=roadmap&markers=color:red%7C'+ Latitude+','+ Longitude}" />
                    </div>
                </div>
            </div>
        </div>

1 个答案:

答案 0 :(得分:0)

避免在视图中进行计算。那就是计算出的可观察量的意思。

例如:

function PostViewModel() {
    var self = this;

    self.Name = ko.observable('');
    self.Address = ko.observable('');
    self.Latitude = ko.observable('foo');
    self.Longitude = ko.observable('bar');

    self.MapImgSrc = ko.computed(function () {
        var la = encodeURIComponent(ko.unwrap(self.Latitude)),
            lo = encodeURIComponent(ko.unwrap(self.Longitude));

        return 'http://maps.googleapis.com/maps/api/staticmap?center=' +
               la + ',' + lo + 
               '&zoom=13&size=300x300&maptype=roadmap&markers=color:red%7C' + 
               la + ',' + lo;
    });
}

<div data-bind='foreach: posts'>
    <div class="well">
        <div class="row">
            <div class="col-xs-12 col-md-12"><h4><span data-bind='text: Name'></span></h4></div>
        </div>
        <div class="row">
            <div class="col-xs-12 col-md-8">
                <div class="row">
                    <div class="col-xs-12 col-md-2"><b>Address:</b></div>
                    <div class="col-xs-12 col-md-10"><span data-bind='text: Address'></span></div>
                </div>
            </div>
            <div class="col-xs-12 col-md-4">
                Longitude: <span data-bind='text: Longitude'></span> -
                Latitude: <span data-bind='text: Latitude'></span>
                <img data-bind="attr: {src:  MapImgSrc}" />
            </div>
        </div>
    </div>
</div>