问题
In Marionette, afaik these two snippets achieve the same purpose:
serializeData: function() {
data = super;
data.foo = "bar";
return data;
}
and
templateHelpers: function() {
return {
foo: "bar"
}
}
What would be the difference and when to use one or the other?
回答1:
In your example I can't think of any practical difference.
Semantically, though, I think that serializeData()
is the better fit when you're transforming the existing model data into something else. It's more complicated to use, because you have to think about the default serialization of the model, which could include a custom model.toJSON()
call. For example, your model might override toJSON
to avoid sending some unneeded data to the server, but if you need that data in the view you will want to add it back with serializaData()
.
templateHelpers
, on the other hand, is more straightforward, since all it does is add new attributes. It makes sense when there's some computed data you want to have available in the template that isn't part of your model.
In the example you cite above, I would use templateHelpers
, because it's a better fit semantically and because it's simpler.
来源:https://stackoverflow.com/questions/32224502/serializedata-vs-templatehelpers