我该如何使用ko.applyBindings?我在使用它时遇到错误

时间:2016-02-15 22:03:25

标签: javascript knockout.js

我的脚本如下:

 @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>


  }

我的外部脚本是:

/**********************************************
* 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

        );






    });
}

这是标记:

   <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 />
}

现在,当我在initialize函数下使用applyBindingsviewModel时,它第一次工作,然后抛出错误&#34;不能为同一元素应用多次绑定。

我试过做一个ko.cleanNode,但那没用。 当我关闭applyBindings时,我没有收到错误,但程序会跳过除最后一页组件之外的所有组件。

1 个答案:

答案 0 :(得分:0)

问题是导致绑定对同一元素应用两次。所以可以在你的代码中使用其他一些敲除绑定,或者initialize函数第二次执行。

如果你想要绑定到你的页面的模型很少,你可以使用applyBindings的第二个参数,如果你没有通过它模型绑定到正文。

  

或者,您可以传递第二个参数来定义要搜索数据绑定属性的文档部分。

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