属性的两种方式绑定,knockout.js [英] Two way binding on attribute, knockout.js

查看:108
本文介绍了属性的两种方式绑定,knockout.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据状态属性的按钮绑定到viewmodel中的observable属性。当我点击按钮时,数据状态属性被改变。但它不影响视图模型。

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

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


解决方案

使用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

这篇关于属性的两种方式绑定,knockout.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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