你如何使用knockout js引用当前元素?

时间:2017-09-19 01:18:24

标签: javascript mvvm knockout.js

我无法访问我存储的地点'阵列。 Locations是一个对象文字,我试图根据我点击的当前元素访问title属性。我有以下代码,但我无法正确地将它发送到console.log。我的猜测是我使用了这个'和封闭功能不强。希望我能够很好地解释这一点,以便有人能够解释一下。任何反馈+解释都非常感谢。

(旁注:我的项目要求说我需要使用淘汰JS框架和MVVM格式)

  1. HTML
  2. 
    
              <ul data-bind="foreach:locationsArray, click:goToLocation">
                <li><span id="place" data-bind="text:title"></span></li>
              </ul>
    &#13;
    &#13;
    &#13;

    2)Javascript ViewModel

    var ViewModel = function() {
    
      var self = this;
    
      self.locationsArray = ko.observableArray(locations);
    
      //My goal here is to log the current title of the location selected from the 
      //model. This is the part that is not working..
      self.goToLocation = function(self) {
        console.log(self.locations);
      }
    

    3)Javascript数据模型(JSON格式)

    var locations = [
      {
        title: 'Nino\'s Pizza',
        location: {
          lat: 40.620057,
          lng: -74.032894
        }
      },
      {
        title: 'Shore Road Bike Path',
        location: {
          lat: 40.623089,
          lng: -74.040596
        }
      },
      {
        title: 'Paneantico Bakery',
        location: {
          lat: 40.619418,
          lng: -74.0322818
        }]
    

1 个答案:

答案 0 :(得分:1)

您需要将点击事件附加到li而不是ul

<ul data-bind="foreach:locationsArray">
  <li><span id="place" data-bind="text:title, click:$parent.goToLocation"></span></li>
</ul>

此处,$parent会告诉淘汰赛在goToLocation而不是ViewModel对象中寻找location

然后在你的js:

var ViewModel = function() {
  var self = this;
  self.locationsArray = ko.observableArray(locations);

  // item will have the data of the clicked li
  self.goToLocation = function(item) {
    console.log(item);
  }
}

ko.applyBindings(new ViewModel());

这是fiddle