首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我应该如何使用ko.applyBindings?我在使用此命令时遇到错误

我应该如何使用ko.applyBindings?我在使用此命令时遇到错误
EN

Stack Overflow用户
提问于 2016-02-16 06:03:25
回答 1查看 52关注 0票数 0

我的脚本如下:

代码语言:javascript
复制
 @using (Html.BeginFooterScripts())
  {
      <script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"></script>
      <script type="text/javascript" src="/Content/Northwestern/js/_libs/knockout.mapping/knockout.mapping.2.4.1.js"></script>
      <script type="text/javascript" src="~/Content/Northwestern/js/views/TabPanel/location-card.js"></script>

          <script type="text/javascript">

              $(function() {
                  initialize();

              });              

          </script>



          <script>
              $(function() {
                  // we must be on a detail page, we don't have a current location, so get it!
                  if (viewModel.currentLocation.latitude == 0 || viewModel.currentLocation.longitude == 0) {
                      geoLocate(function(location) {
                          viewModel.currentLocation.latitude = location.coords.latitude;
                          viewModel.currentLocation.longitude = location.coords.longitude;

                          displayLocation('@Model.LocationId');
                      }, geoLocateError);
                  } else {
                      displayLocation('@Model.LocationId');
                  }
              });
          </script>


  }

我的外部脚本是:

代码语言:javascript
复制
/**********************************************
* Global variables
**********************************************/

var applied = false;
var geoLocateError = function onError(error) {
    alert(error.message);
};

function ViewModel() {
    var self = this;
    self.currentLocation = {
        latitude: 0,
        longitude: 0
    };
    self.LocationId = ko.observable();

}

var viewModel = new ViewModel();


$(function () {

});

function initialize() {
    ko.applyBindings(viewModel); 
    geoLocate(function(location) {
        initLocation(location);       
    }, geoLocateError);


}

/**********************************************
* Location Functions
**********************************************/
function initLocation(location) {
    viewModel.currentLocation = {
        latitude: location.coords.latitude,
        longitude: location.coords.longitude
    };

}


function displayLocation(id) {
    var apiUrl = '/api/northwestern/locations/getlocationbyid/' + id;

    var data = {
        'latitude': viewModel.currentLocation.latitude,
        'longitude': viewModel.currentLocation.longitude
    };

    self.LocationId = id;

    $.getJSON(apiUrl, data, function (response) {
        var fragment = document.createDocumentFragment(),
            container = document.createElement('div'),
            viewModel = response;
        fragment.appendChild(container);

        // merge together all the display types into a commma-separated list
        response.TypeListDisplay = $.map(response.Types, function (obj, t) {
            return obj.ItemName;
        }).join(', ');

        ko.renderTemplate(
            "location-detail-template",
            viewModel, {
                afterRender: function () {
                    $('#detail-container').html(container.innerHTML);
                }
            },
            container

        );






    });
}

下面是标记:

代码语言:javascript
复制
   <div class="row">
        <div class="col md-4">
            <div class="section-content">
                <div id="detail-container">
                </div>
            </div>

            <script type="text/html" id="location-detail-template">
                <div class="card card-locations-alt">
                    <div class="card-content">
                        <figure class="map">
                            <a target="_blank" href="https://www.google.com/maps/dir/Current+Location/@Model.Location.Latitude, @Model.Location.Longitude">
                                <img src="https://maps.googleapis.com/maps/api/staticmap?center=@Model.Location.Latitude,@Model.Location.Longitude&zoom=13&size=65x65&maptype=roadmap&markers=color:0x776EA7%7Clabel:%7C @Model.Location.Latitude,@Model.Location.Longitude">
                            </a>
                        </figure>
                        <div class="location-content" itemscope="" itemtype="http://schema.org/LocalBusiness">
                            <div class="location-name">
                                <h2 class="location-title" itemprop="name" data-bind="text: ItemName"></h2>
                            </div>
                            <div class="distance">
                                <i class="material-icons">place</i> <span data-bind="text: Distance.toFixed(1)"> Mi</span>
                            </div>
                            <div class="location-phone">
                                <a data-bind="attr: { 'href': clickToCallify(Phone), 'data-track-event': 'Find a Location - Detail', 'data-track-action': 'call icon' }" class="tel" itemprop="telephone"></a>
                            </div>
                        </div>
                        <div class="location-actions flex-container align-center no-print">
                            <a class="locations-icon flex-item tel" href="tel:8475358000">
                                <div class="call-icon uppercase">
                                    <i class="material-icons">phone</i><br>
                                    call
                                </div>
                            </a>
                            <a data-bind="attr: {'href' : 'https://www.google.com/maps/dir/Current+Location/' + Latitude + ',' + Longitude, 'data-track' : 'Find a Location', 'data-track-action' : 'directions', 'data-track-label' : ItemName }" target="_blank" class="locations-icon flex-item uppercase">
                                <i class="material-icons">directions</i><br>
                                directions
                            </a>
                            <a href="" class="location-detail locations-icon flex-item uppercase">
                                <i class="material-icons">info</i><br>
                                details
                            </a>
                        </div>
                    </div>

                </div>

            </script> 
        </div>
        <div class="col md-7">

            @(new HtmlString(Model.Body))

        </div>

    </div>

    <br />
}

现在,当I applyBindingsviewModel)在initialize函数下时,它第一次工作,然后抛出一个错误“无法对同一元素多次应用绑定。

我曾尝试做一个ko.cleanNode,但没有起作用。当我取下applyBindings时,我没有得到这个错误,但是程序跳过了除最后一个页面组件之外的所有页面。

EN

回答 1

Stack Overflow用户

发布于 2016-02-16 06:17:28

这个问题是因为绑定对相同的元素应用了两次。因此,可以是代码中的某些其他敲除绑定,或者第二次执行initialize函数。

如果你有几个模型想要绑定到你的页面上,你可以使用applyBindings的第二个参数,如果你不把它传递给body模型绑定。

还可以传递第二个参数,以定义要在文档的哪个部分搜索数据绑定属性。

http://knockoutjs.com/documentation/observables.html

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35419933

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档