限制视图中的字符数(Backbone.js)

Limit number of characters in View (Backbone.js)

本文关键字:Backbone js 字符 视图      更新时间:2023-09-26

我有一个backbone.js视图,它从HTML文件中读取模板,并将其模型中的值插入到模板中。其中一个值在变量title中,其长度可能足以中断页面上的元素流。我想使用Javascript来限制title的最大字符数,而不是在后端进行,因为最终必须显示完整的title

在模板渲染后,我尝试选择包含title的div,但似乎无法选择。否则怎么办?

模板

<script type="text/template" id="tpl_PhotoListItemView">
    <div class="photo_stats_title"><%= title %></div>
</script>

查看

PhotoListItemView = Backbone.View.extend({
    tagNAme: 'div',
    className: 'photo_box',
    template: _.template( $('#tpl_PhotoListItemView').html() ),
    render: function() {
        $(this.el).html( this.template( this.model.toJSON() ) );
        console.log($(this.el).children('.photo_stats_title')); <!-- returns nothing -->
        this.limitChars();
        return this;
    },
    limitChars: function() {
        var shortTitle = $(this.el).children('.photo_stats_title').html().substring(0, 10);
        $(this.el .photo_stats_title).html(shortTitle);
    }
});

与其在渲染后尝试修改标题,不如在渲染时对其进行修改。

maxlength变量也传递到模板,然后:

<script type="text/template" id="tpl_PhotoListItemView">
    <div class="photo_stats_title"><%= title.substr(0,maxLength) %></div>
</script>

如果title.length小于maxlength,则会显示整个字符串。如果大于,则仅显示前maxlength个字符。

或者,只需将title的最大长度硬编码到对.substr() 的调用中

如果你需要执行更高级的截断(例如,在截断的标题中添加"…"),你最好在呈现模板之前修改标题,将标题的截断版本传递到模板中

另一种选择是覆盖Model.parse(response),在模型上创建shortTitle属性;这样,每当您使用模型时,它总是可用的

有两件事,第一件事,我建议你用这种方式来获得任何View的子项,而不是你正在做的:

console.log( this.$('.photo_stats_title') );

"this.$"是一个具有特定视图范围的jQuery选择器。

第二件事是包装你的模型来处理这个问题,我不建议在你的模板或视图中验证它。在您的模型中为shortTitle定义一个新属性:

var titleMaxLength = 20;
var YourModel : Backbone.Model.extend({
    defaults : {
        id          : null,
        shortTitle  : null,
        title       : null
    },
    initialize : function(){
        _.bindAll(this);
        this.on('change:name', this.changeHandler);
        this.changeHandler();
    },
    changeHandler : function(){
        var shortTitle = null;
        if( this.title ){
            shortTitle = this.title.substr(0, titleMaxLength);
        }
        this.set({ shortTitle : shortTitle }, {silent: true});
    }
});