且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

属性的两种方式绑定,knockout.js

更新时间:2023-02-27 09:10:29

使用KO时, viewModel然后演示文稿将被改变。
因此,当用户点击按钮时,您应该更改虚拟机:



如果您的VM如下所示:

  var vm = function(){
var self = this;
self.status = ko.observable(false);
self.toggleStatus = function(){self.status(!self.status());你的html应该是这样的:
 < button id =changeStatusdata-bind =click:toggleStatus/> 

如果您有多个按钮,您可以更改函数以获取obj:

  var vm = function(){
var self = this;
self.status = ko.observable(false);
self.flag = ko.observable(false);
self.toggleStatus = function(data,event,obj){self [obj](!self [obj]()); } b


$ b

让我知道您是否需要更多信息


I have a button with a data-status attribute that is bind to a observable property in a viewmodel. When I click on the button the data-status attribute is changed. But it does not affect the viewmodel. How to do if I want the viewmodel to be updated with the new value?

<button id="changeStatus" data-status="0" data-bind="attr: {'data-status', Status}" />

$("#changeStatus").attr("data-status",1);

When working with KO, the idea is to change the viewModel and then the presentation will be changed. So when the user clicks on the button you should change the VM:

if your VM looks like this:

var vm = function () {
var self = this;
self.status=ko.observable(false);
self.toggleStatus=function(){ self.status(!self.status()); } 

}

your html should look like this:

<button id="changeStatus" data-bind="click: toggleStatus" />

if you have several buttons, you can change the function to get the obj:

var vm = function () {
var self = this;
self.status=ko.observable(false);
self.flag=ko.observable(false);
self.toggleStatus=function(data,event,obj){ self[obj](!self[obj]()); } 

}

<button data-bind="click: function(d,e){ togglebutton(d,e,'status');}" />
<button data-bind="click: function(d,e){ togglebutton(d,e,'flag');}" />

let me know if you need more info