【问题标题】:Titanium / Backbone: Ensure that a property on a model always has it's type convertedTitanium / Backbone:确保模型上的属性始终具有类型转换
【发布时间】:2017-01-18 07:09:21
【问题描述】:

我有一个使用合金模型创建的 Titanium/Appcelerator 应用程序,它使用 Backbone.js。每个模型都有一个文本字段,我想将其解释为数字。到目前为止,我一直在获取该属性并在每次需要使用它时使用 parseInt() 对其进行转换。

有没有办法在我每次访问该属性时自动将该属性解释为一个数字?也许某种自动转换?我想避免更改数据库中字段的类型而不得不进行某种迁移。

这是我的模型的精简示例。属性date 作为字符串保存到数据库中。但因为它是 UTC 时间戳,所以我想始终将其解释为数字。

exports.definition = {
    config: {
        columns: {
            "name": "text",
            "date": "text" 
        },
        adapter: {
            type: "sql",
            collection_name: "people"
        }
    },
    extendModel: function(Model) {
        _.extend(Model.prototype, {
            // extended functions and properties go here
        });

        return Model;
    },
    extendCollection: function(Collection) {
        _.extend(Collection.prototype, {
            // extended functions and properties go 
        });

        return Collection;
    }
};

【问题讨论】:

标签: javascript backbone.js titanium appcelerator backbone-model


【解决方案1】:

你可以像这样扩展你的模型:

exports.definition = {
   config: {
    columns: {
        "name": "text",
        "date": "text" 
    },
    adapter: {
        type: "sql",
        collection_name: "people"
    }
  },

  extendModel: function(Model) {
    _.extend(Model.prototype, {

        transform: function transform() {
           var transformed = this.toJSON();
           transformed.date = parseInt(transformed.date);
           return transformed;
        }
    });
    return Model;
  },

  extendCollection: function(Collection) {
    _.extend(Collection.prototype, {
        // extended functions and properties go 
    });

    return Collection;
  }
};

您可以在 UI 元素上使用 dataTransform read here 属性来应用转换方法。

view.xml

<Alloy>
    <Collection src="your_collection_name" />
    <Window class="container">
        <TableView dataCollection="your_collection_name" dataTransform="transformFunction">

        </TableView>
    </Window>
</Alloy>

view.js

function transformFunction(model) {
    var transformed = this.toJSON();
        transformed.date = parseInt(transformed.date);

    return transformed;
}

这是您可以使用您的转换方法来修改属性的方式,或者您也可以将任何自定义属性添加到您的模型并以相同的名称引用它。

【讨论】:

  • 它对我不起作用,我在转换方法中放了一个console.log,看起来它没有被调用。我错过了一步吗?
  • @shrewdbeans - 我添加了一个代码来根据您的要求修改模型。试着告诉我。
  • 这适用于 TableView 上的数据绑定,但不幸的是,每次我以另一种方式(例如通过排序方法)访问日期值时,它仍然以字符串形式出现。有没有办法总是 确保它以字符串形式出现。我也仍然没有看到正在调用的模型扩展方法中的 transform 方法。感谢您的帮助。
  • 我认为不可能直接检索字符串的整数值。无论如何,您都需要扩展数据绑定中的方法,或者您可以在 model.map 方法中将字符串转换为 int。处理此问题的最简单方法是将 date 列更改为 "date": "integer" 因为通过采用整数格式,您无需将其转换为字符串。
  • 如果我将表的日期列从字符串更改为整数,这会对数据库产生不利影响吗?我知道存储在列中的字符串只包含数字,没有其他字符。
猜你喜欢
  • 2020-01-11
  • 2021-02-13
  • 2018-06-25
  • 2019-05-29
  • 1970-01-01
  • 2015-09-28
  • 2017-08-08
  • 1970-01-01
相关资源
最近更新 更多