如何操纵DOM来利用MVVM模式,我想使用Knockout的点击绑定来实现这个片段

时间:2016-12-30 07:44:36

标签: javascript mvvm knockout.js

如何操纵DOM以利用MVVM模式,我想使用Knockout的点击绑定来实现这个片段。我不想使用jQuery或JavaScript DOM方法。我正在接受http://knockoutjs.com/documentation/click-binding.html

的帮助



var viewModel = function() {
    var self = this;
    var geocoder = new google.maps.Geocoder();
    document.getElementById('search-me').addEventListener('click', function() {
        self.geoAddr(geocoder, map);
    });
}

<input class="text-box" id="location" type="text" value="Delhi, India">
<button class="my-button" id="search-me" type="submit">
        <img class="search-img" src="image/mybutton.png" alt="search" />
</button>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

不确定你到底是什么,但是

&#13;
&#13;
function model() {
  var self = this;
  this.location = ko.observable('Delhi, India');
  this.geoAddr = function() {
    var location = self.location();
    alert('my location is ' + location);
  }
}

var mymodel = new model();

$(document).ready(function() {
  ko.applyBindings(mymodel);
});
&#13;
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <label class="control-label col-sm-2" for="location">Location:</label>
  <div class="col-sm-9">
    <input type="text" class="form-control" id="location" data-bind="textInput: location" />
  </div>
</div>
<input type="button" class="btn btn-info" value="Search" data-bind="click: geoAddr">
&#13;
&#13;
&#13;