Backbone.js - 自定义设置器

发布于 2024-12-11 14:54:02 字数 645 浏览 0 评论 0原文

想象一个简单的骨干模型,就像

window.model= Backbone.Model.extend({
   defaults:{
      name: "",
      date: new Date().valueOf()
   }
})

我试图找到一种方法来始终使模型以小写形式存储名称,而不管提供的输入如何。即,

model.set({name: "AbCd"})
model.get("name") // prints "AbCd" = current behavior
model.get("name") // print "abcd" = required behavior

这样做的最佳方法是什么?这就是我能想到的:

  1. 覆盖“set”方法
  2. 使用“SantizedModel”来侦听此基本模型上的更改并存储清理后的输入。然后,所有视图代码都将传递给这个经过净化的模型。

我提到的特定“小写”示例在技术上可能在检索它时由视图更好地处理,但想象一下不同的情况,例如,用户输入以英镑为单位的值,而我只想将值以 $s 存储在我的数据库中。对于同一模型也可能有不同的视图,我不想在使用它的任何地方都必须执行“toLowerCase”。

想法?

Imagine a simple backbone model like

window.model= Backbone.Model.extend({
   defaults:{
      name: "",
      date: new Date().valueOf()
   }
})

I'm trying to find a way to always make the model store the name in lower-case irrespective of input provided. i.e.,

model.set({name: "AbCd"})
model.get("name") // prints "AbCd" = current behavior
model.get("name") // print "abcd" = required behavior

What's the best way of doing this? Here's all I could think of:

  1. Override the "set" method
  2. Use a "SantizedModel" which listens for changes on this base model and stores the sanitized inputs. All view code would then be passed this sanitized model instead.

The specific "to lower case" example I mentioned may technically be better handled by the view while retrieving it, but imagine a different case where, say, user enters values in Pounds and I only want to store values in $s in my database. There may also be different views for the same model and I don't want to have to do a "toLowerCase" everywhere its being used.

Thoughts?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

醉梦枕江山 2024-12-18 14:54:02

更新:您可以使用插件:https://github.com/berzniz/backbone .getters.setters


您可以像这样重写 set 方法(将其添加到您的模型中):

set: function(key, value, options) {
    // Normalize the key-value into an object
    if (_.isObject(key) || key == null) {
        attrs = key;
        options = value;
    } else {
        attrs = {};
        attrs[key] = value;
    }

    // Go over all the set attributes and make your changes
    for (attr in attrs) {
        if (attr == 'name') {
            attrs['name'] = attrs['name'].toLowerCase();
        }
    }

    return Backbone.Model.prototype.set.call(this, attrs, options);
}

UPDATE: you can use the plug-in: https://github.com/berzniz/backbone.getters.setters


You can override the set method like this (add it to your models):

set: function(key, value, options) {
    // Normalize the key-value into an object
    if (_.isObject(key) || key == null) {
        attrs = key;
        options = value;
    } else {
        attrs = {};
        attrs[key] = value;
    }

    // Go over all the set attributes and make your changes
    for (attr in attrs) {
        if (attr == 'name') {
            attrs['name'] = attrs['name'].toLowerCase();
        }
    }

    return Backbone.Model.prototype.set.call(this, attrs, options);
}
柒夜笙歌凉 2024-12-18 14:54:02

这将是一个黑客,因为这不是它的目的,但你总是可以为此使用验证器:

window.model= Backbone.Model.extend({
   validate: function(attrs) {
      if(attrs.name) {
         attrs.name = attrs.name.toLowerCase()
      }

      return true;
   }
})

验证函数将被调用(只要 silent 选项不存在) set) 在模型中设置值之前,因此它让您有机会在数据真正设置之前改变数据。

It would be a hack, because this isn't what it was made for, but you could always use a validator for this:

window.model= Backbone.Model.extend({
   validate: function(attrs) {
      if(attrs.name) {
         attrs.name = attrs.name.toLowerCase()
      }

      return true;
   }
})

The validate function will get called (as long as the silent option isn't set) before the value is set in the model, so it gives you a chance to mutate the data before it gets really set.

︶葆Ⅱㄣ 2024-12-18 14:54:02

不是为了自吹自擂,而是我创建了一个具有“计算”属性的 Backbone 模型来解决这个问题这。换句话说,

var bm = Backbone.Model.extend({
  defaults: {
     fullName: function(){return this.firstName + " " + this.lastName},
     lowerCaseName: function(){
        //Should probably belong in the view
        return this.firstName.toLowerCase();  

     }
   }
})

您还监听计算属性的更改,并且几乎只是将其视为常规属性。

提到的插件 Bereznitskey 也是一种有效的方法。

Not to toot my own horn, but I created a Backbone model with "Computed" properties to get around this. In other words

var bm = Backbone.Model.extend({
  defaults: {
     fullName: function(){return this.firstName + " " + this.lastName},
     lowerCaseName: function(){
        //Should probably belong in the view
        return this.firstName.toLowerCase();  

     }
   }
})

You also listen for changes on computed properties and pretty much just treat this as a regular one.

The plugin Bereznitskey mentioned is also a valid approach.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文