如何在模板中使用自定义模型属性

如何在模板中使用自定义模型属性

本文介绍了Backbone.js的 - 如何在模板中使用自定义模型属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

这可能是一个非常简单的问题,但我有一个时间赫克找到答案。

This might be a really simple question but I'm having a heck of a time finding an answer.

,我有这样的行:

Person = Backbone.Model.extend();

然后我用从一个URL填补了收藏。对于这个例子的目的,说我有一个姓氏和名字,我想要做的事,如:

I then use that in a collection filled from a URL. For the sake of the example, say I have a first and last name, and I want to do something like:

Person = Backbone.Model.extend({
    FullName: this.get("firstName") + " " + this.get("lastName")
});

我可以调用内部的骨干使用,例如,People.first()。全名()。但是,如果我通过People.first(),以我的观点,并呈现在一个模板,它似乎已经没有什么知识是全名。

I can call that inside backbone using, for example, People.first().FullName(). But if I pass People.first() to my view and render that in a template, it seems to have no knowledge what FullName is.

我将如何自定义属性添加到骨干模型,并使用该模板里面呢?

How would I add a custom property to a model in Backbone and use that inside a template?

干杯!

推荐答案

全名定义没有任何意义的,所以我会认为你的真正用意这样的:

Your FullName definition doesn't make any sense so I'm going to assume that you really meant this:

Person = Backbone.Model.extend({
    FullName: function() {
        return this.get("firstName") + " " + this.get("lastName");
    }
});

通常你会打电话给您的模型连载他们通过一个模板使用:

Usually you'll call toJSON on your models to serialize them for use by a template:

var html = template({ person: person.toJSON() })

的toJSON 简单地返回模型的内部属性的(浅)拷贝。这些属性将,presumably,同时拥有的firstName 的lastName 属性,但全名是在模型上,这样就不会在属性的功能。

The default toJSON simply returns a (shallow) copy of the model's internal attributes. The attributes will, presumably, have both firstName and lastName properties but FullName is a function on the model so it won't be in the attributes.

您可以提供自己的的toJSON

toJSON: function() {
    var j = _(this.attributes).clone();
    j.FullName = this.FullName();
    return j;
}

,然后你会在你的模板有一个全名。然而,的toJSON 也用来序列模型将数据发​​送到服务器;你的服务器最终将看到全名,它可能生气了一番。你可以专门增加一个序列化的模板:

and then you'd have a FullName in your template. However, toJSON is also used to serialize the model to send data to the server; your server would end up seeing a FullName and it might get upset about that. You could add another serializer specifically for templates:

// `serialize` is another common name for this
for_template: function() {
    var j = this.toJSON();
    j.FullName = this.FullName();
    return j;
}

,然后使用该功能为您提供的模板数据:

and then use that function to supply data for your templates:

var html = template({ person: person.for_template() });

这篇关于Backbone.js的 - 如何在模板中使用自定义模型属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 13:49