如何确定模型在模板中是否是新模型?

问题描述 投票:1回答:1

如果我的模型是新模型还是现有模型,我想在模板中显示特定元素。

我试图显示{{ id }}{{ cid }}{{ isNew }},但它们都是空的。

以下是示例:

// The Model
var MyModel = Backbone.Model.extend({});

// In the view
var model = new Contact();
this.$el.empty().append(this.template(model.toJSON()));

// The template :
{{#if isNew}}New model{{/if}}

我该如何测试?

javascript templates backbone.js
1个回答
2
投票

这是我想出的解决方案:

// The Model
var MyModel = Backbone.Model.extend({
    'toJSON': function () {
    // Copied from the source
    var obj = _.clone(this.attributes);

    obj['isNew'] = this.isNew();
    return obj;
    }
});

当然,这确保该模型没有属性“ isNew”;)

© www.soinside.com 2019 - 2024. All rights reserved.