如何转换1为true或0为假时取模型 [英] How to convert 1 to true or 0 to false upon model fetch
问题描述
我有一个设定从MySQL数据库中的JSON响应的模型。该模型数据被设置以真或假到数据库的布尔/ TINYINT字段,它采用1或0
I have a model that is set with a JSON response from a mysql database. The model data is set with true or false into a boolean/tinyint field in the database, which uses 1 or 0.
在我看来,我有一个绑定,对于具有下划线的_.isBoolean一个布尔检查。当然,当我的模型接收到的数据,将其设置为1或0,而不是真或假和_.isBoolean检查失败。
In my view, I have a binding that checks for a boolean with underscore's _.isBoolean. Of course, when my model receives the data, it is set with 1 or 0 instead of true or false and the _.isBoolean check fails.
反正要么正确有从MySQL我的JSON响应是一个true或false值,而不是1或0,preferably,有没有办法让我的模型更新本身在获取(和前视图渲染)的基础上它的1或0财产投真的还是假的?
Is there anyway to either correctly have my JSON response from mysql be a boolean true or false value instead of 1 or 0, or preferably, is there a way to have my model update itself upon fetch (and before the view renders) to cast true or false based on it's 1 or 0 property?
例如。我的模型的数据看起来像 {器isChecked:1}
,当我需要它是 {器isChecked:真正}
e.g. my model's data looks like {"isChecked":"1"}
when I need it to be {"isChecked":true}
感谢您大为你可能有任何建议!
Thank you greatly for any suggestions you may have!
推荐答案
所有你需要的是转换字符串
到 INT
与 +
并转换的结果与布尔 !!
:
All you need is convert string
to int
with +
and convert the result to boolean with !!
:
var response = {"isChecked":"1"};
response.isChecked = !!+response.isChecked
您可以做到这一点的操作在解析
方法:
You can do this manipulation in the parse
method:
parse : function (response) {
response.isChecked = !!+response.isChecked;
return response;
}
这篇关于如何转换1为true或0为假时取模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!