KnockoutJS中的可见绑定无法正常工作? [英] Visible binding in KnockoutJS does not work properly?

查看:50
本文介绍了KnockoutJS中的可见绑定无法正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个下拉框,其中包括狗",猫",熊".当用户选择猫"或狗"时,我想在选择框的前面显示一个输入框.所以我正在使用可见的绑定来做到这一点:

I have a drop down box including 'dog', 'cat', 'bear'. I want to show an input box in front of the select box when the user select 'cat' or 'dog'. So I am using the visible binding to do this:

<select data-bind="options:animals, value: animal"</select>
<input data-bind="value: description, visible: showDescription"/>

self.showDescription=ko.observable(false);

self.showOtherDescription = function() {
   if(animal == 'cat' || animal == 'dog'){
     self.showDescription=ko.observable(true);
   }
}

页面加载时正在工作.但是,当我从下拉菜单中将选项更改为"bear"时,它不会隐藏输入框.有人有什么主意吗?

It is working when the page is loaded. But when I change the option to 'bear' from the drop down it does not hide the input box. Does anybody have any idea?

推荐答案

这是去IMO的方法:

var ViewModel = function() {
  var self = this;
  
  self.animals = ['', 'cat', 'dog', 'mouse', 'bird'];
  
  self.animal = ko.observable('');
  
  self.description = ko.observable('');

  self.showOtherDescription = ko.computed(function() {
    return self.animal() === 'cat' || self.animal() === 'dog';
  });
};

ko.applyBindings(new ViewModel());

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<select data-bind="options: animals, value: animal"></select>
<input data-bind="value: description, visible: showOtherDescription"/>

它会更改/在代码中添加一些内容:

It changes / adds a few things to your code:

  • 至少在您发布的内容中不需要showDescription
  • showOtherDescription必须为computed,因此在更新依赖项时会对其进行更新;
  • showOtherDescription不应具有设定者"功能或改变其他可观察物的副作用.如果您确实需要这样的二传手,请查看 writeable 计算出的可观察值;
  • 如果将animal用作双向绑定属性,则它必须是observable,因此需要作为函数调用以获取其值.
  • 我不确定您发布的代码将如何工作,就像在View中使用animal == 'cat' 之类的animal一样.我认为它可能应该在ViewModel上公开公开,因此您应该将其称为self.animal.
  • The showDescription is not needed, at least not in the context of the things you've posted;
  • The showOtherDescription needs to be a computed so it's updated when dependencies are updated;
  • showOtherDescription should not have a "setter" function or side-effects that change other observables. If you do need such a setter, check out writeable computed observables;
  • If you use animal as a two-way bound property, it needs to be an observable and thus needs to be invoked as a function to get its value.
  • I'm not sure how the code you posted would work, as refer to animal like animal == 'cat' as well as use it in the View. I think it should probably be exposed publicly on the ViewModel, and as such you should refer to it as self.animal.

这篇关于KnockoutJS中的可见绑定无法正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆