【问题标题】:Knockout JS and observable radio buttonsKnockout JS 和可观察的单选按钮
【发布时间】:2016-10-21 15:23:01
【问题描述】:

我正在制作一个小应用程序,它将询问用户位置存储,直到单击单选按钮,然后调用谷歌地图 api 以列出附近选中的单选按钮的位置。

到目前为止,我有一个全局对象var food = { mexican: "mexican food", pizza: "italian food", coffee: { venue: "cafe", keyword: "coffee" } };

帮助我传递给 api 调用中的全局变量 var queryL;。

var viewModel = function() {
  food: ko.observable

现在我已经走到了这一步,需要一些帮助来找出三个单选按钮并更改值。

在伪代码中类似于:

    if (mexican is checked) {  
     queryL = food.mexican;
     initmap();
} else if (pizza is checked) {
     queryL = food.pizza;
     initmap();
} else if (coffee is checked) {
     queryL = food.coffee.keyword;
     typeL = food.coffee.venue;
     initmap();
}

我将如何做到这一点?

<label class="radio-inline"><input type="radio" name="optradio" value="mexican" data-bind="checked: typeOfFood">Tacos</input></label>
<label class="radio-inline"><input type="radio" name="optradio" value="pizza" data-bind="checked: typeOfFood">Pizza</input></label>
<label class="radio-inline"><input type="radio" name="optradio" value="coffee" data-bind="checked: typeOfFood">Coffee</input></label>

单选按钮^^

感谢您的帮助!

【问题讨论】:

    标签: javascript jquery knockout.js


    【解决方案1】:

    您可以订阅您的typeOfFood observable,并将您的逻辑包含在订阅回调函数中。

    这里是一个例子:https://jsfiddle.net/kyr6w2x3/98/

    var viewModel = function (){
     var self = this;
     self.food = ko.observable(food);
     self.queryL = ko.observable('');
     self.typeL  = ko.observable('');
     self.typeOfFood = ko.observable();
    
     self.typeOfFood.subscribe(function(newValue){
        switch(newValue){
          case "mexican":
          //do your stuff here
          self.queryL(self.food().mexican);
          self.initMap();
          break;
        case "pizza":
          //do your stuff here
          self.queryL(self.food().pizza);
          self.initMap();
          break;
        case "coffee":
          //do your stuff here
          self.queryL(self.food().coffee.keyword);
          self.typeL(self.food().coffee.venue);
          self.initMap();
          break;
        }
      })
    
     self.initMap = function(){
       // your initMap Function here
       console.log("inside initMap function");
       console.log("queryL: " , self.queryL());
       console.log("typeL: " , self.typeL());
     }
    }
    ko.applyBindings(viewModel);
    

    【讨论】:

      猜你喜欢
      • 2016-02-29
      • 2011-07-12
      • 2014-06-22
      • 1970-01-01
      • 1970-01-01
      • 2018-09-08
      • 2014-01-28
      • 2012-12-19
      相关资源
      最近更新 更多