【问题标题】:preprocessing models in backbone主干中的预处理模型
【发布时间】:2013-10-22 13:15:21
【问题描述】:

什么是对模型的字段进行一些预处理的好方法。例如,假设我有这个数据:

[{
        id: '1',
        sender: 'me',
        receiver: 'you',
        message: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum",
        date: new Date("October 13, 1975 11:13:00").toLocaleDateString()
    }]

在这个简单的模型中:

App.Models.Notification = Backbone.Model.extend({
    defaults: {
        'date': new Date()
    }
});

我想减少message 值中的字符数,以便在视图中显示它,但前提是该消息包含超过给定数量的字符。也许是这样的:

if ( this.model.get('message').trim().split(" ").length > 30 ) {
  // code here
}

所以,我不想在所有模型中都执行该预处理。在我看来我应该这样做吗?如果是这样,怎么做?我有read 一些解决方案,但其中一些不适用于这种情况,而另一些似乎是一种黑客攻击。

谢谢!

更新

根据 Alex 的建议并作为参考,我在这里举了一个使用 Handlebars 模板助手的示例:

render: function() {

    Handlebars.registerHelper('getShort', function(options) {
        if ( options.fn(this).trim().split(" ").length > 30 ) {
            var message = options.fn(this);
            var shortText = $('<div/>', { text: message })
            .html()
            .trim()
            .substring(0, 200)
            .split(" ")
            .slice(0, -1)
            .join(" ") + "..."

            return shortText;
        }
        return options.fn(this);
    });

    template = Handlebars.compile( $("#my-template").html() );
    this.$el.html( template( this.model.toJSON() ));
    return this;
}

并像这样使用它:

index.html

{{#getShort}}{{message}}{{/getShort}}

【问题讨论】:

    标签: javascript backbone.js preprocessor


    【解决方案1】:

    如果您的库堆栈支持这种表示逻辑,则应将其放入模板助手中。如果没有,只需添加getShortenedMessage(length) 方法来建模并使用它来获取您的价值。无论如何,不​​要为了显示不同而更改实际模型属性——这是糟糕的设计,以后可能会导致各种复杂情况。

    【讨论】:

    • 没错。我不想更改模型,因为它可能会在保存它时导致不需要的行为,但是,我不能真正将 getShortenedMessage 添加到模型中,因为这会影响依赖这些模型的每个集合,对吗?正如我所说,我想避免这种情况。
    • 您是否考虑过将此方法添加到 MyModel 这样的类中并扩展它而不是原版 Backbone.Model
    • +1 用于使用(或创建)模板助手。如果您严格地希望缩短用于表示的消息字段,它可能属于表示层。
    • 不确定扩展 MyModel 是什么意思。你的意思是使用 javascript 原型而不是 Backbone 的扩展?顺便说一句,模板助手看起来不错。我正在使用下划线,所以我想这还不够好。也许使用车把?
    【解决方案2】:

    最好将这种逻辑放入外部辅助函数中,然后将结果传递到您的模板中。

    例如,如果你有这样的事情:

    var NotificationHelper = {
        trimmedMessage: function (notification, limit) {
            // do trimming logic here based on notification.get('message')
            return value;
        }
        ... // other helper functions
    };
    

    给定一个这样的模板:

    template: _.template('<p><%- message %></p><p><%= foo %></p>'),
    

    然后在您的视图代码中,您可以执行以下操作:

    this.$el.html( this.template({
        message: NotificationHelper.trimmedMessage(this.model),
        foo: this.model.get('foo')
    });
    

    我会倾向于获得具有多种功能的视图助手。它有助于将表示逻辑排除在模型之外。通过将计算出的值传递到您的模板中,这将使您的模板更具可读性和可管理性。

    此外,诸如截断文本之类的内容可以放在非模型特定的帮助器中,因为它是非常通用的功能类型。

    【讨论】:

    • 我喜欢这个。这比使用 Handlebars 的模板助手需要更多的工作,但这是一个非常好的选择。谢谢!
    【解决方案3】:

    您可以使用underscore.string 库 (Link)

    基本上,您可以简单地在渲染函数中调用函数 truncate/prune (Link),它会返回缩短的版本..

    render: function() {
         var shortenedMessage = _('Hello, world').prune(8); // => 'Hello...'
    }
    

    如果消息长度不超过字符数,它只返回字符串。 请注意,您也可以将其与Underscore.js 一起使用。

    【讨论】:

    • 惊人的图书馆。谢谢!
    【解决方案4】:

    通常最好在模型中有一个函数。这样,任何使用该模型的人都可以重用它。模板可以调用函数,它只会在你需要的时候被处理。

    App.Models.Notification = Backbone.Model.extend({
        defaults: {
            get shortdate() {
                // put the code here to return the custom date format
            }
        }
    });
    
    // in the template (or anywhere else)
    <div id='date'><%= Notification.shortdate %></div>
    

    对于奖励积分,请使用自定义 getter(在 IE9+ 中受支持)。所以它看起来像一个属性,但只在函数被调用时处理它。由于没有setter,所以无法设置。

    【讨论】:

      【解决方案5】:

      创建一个模型构造函数,如果字符串太长,则在将其设置在构造函数中之前将其缩短。有关Model 构造函数的更多信息,请参阅此page

      【讨论】:

      • 但这会修改​​使用这些模型的每个集合,对吗?正如我之前所说,我想避免这种情况。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-06
      • 2018-12-07
      • 1970-01-01
      • 2015-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多