gpt4 book ai didi

javascript - Backbone 中的计算属性

转载 作者:行者123 更新时间:2023-12-02 18:09:35 24 4
gpt4 key购买 nike

我有一个场景,在客户端上操作的数据的呈现方式和交互方式与在服务器上呈现的方式不同。

考虑以下从服务器返回的事件资源。

{
"id": 123,
"start_at": 1331336004906,
"end_at": 1331337704906
}

以及以下用于编辑的模板:

<form>
<!-- Notice how date and time are separated in the interface -->
<input type="text" name="start_date" value="{{start_date}}" />
<input type="text" name="start_time" value="{{start_time}}" />

<!-- Instead of asking for an end date/time, we ask for the duration -->
<input type="text" name="duration" value="{{duration}}" />

<input type="submit" />
</form>

如何将 start_datestart_timeduration 视为 Backbone 模型中的属性,而不将它们发送到服务器?我应该修改 .toJSON() 吗?

最佳答案

我将initialize()函数与更改事件监听器结合使用来更新派生属性。这个想法首先是在模型初始化时计算属性,其次是让模型监听自己的变化并相应地更新属性。

我的解决方案大致如下:

MyModel: Backbone.Model.extend({
initialize: function() {
this.updateDerivedAttributes();
this.on('change:start_at', this.updateDerivedAttributes, this);
},
updateDerivedAttributes: function() {
this.set({
start_date: Utils.dateFromDate( this.get( "start_at" ) ),
start_time: Utils.timeFromDate( this.get( "start_at" ) ),
duration: Utils.youGetTheIdea()
}, {silent:true});
}
});

关于javascript - Backbone 中的计算属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9642439/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com