Still learning backbone so bear with me;
I'm trying to add a new model with blank fields to a view, but the template I've created has a whole bunch of
<input value="<%= some_value %>" type="whatever" />
Works perfectly fine when fetching data, it populates it and all goes well. The trouble arises when I want to create a new (blank) rendered view, it gives me
Uncaught ReferenceError: some_value is not defined
I can set defaults
(I do already for a few that have default values in the db) but that means typing out over 40 of them with blanks; is there a better way of handling this?
I'm fiddling around with the underscore template itself, trying something like <%= if(some_value != undefined){ some_value } %>
but that also seems a bit cumbersome.
You can abstract @Dmitri's answer further by adding a function to your model and using it in your template.
For example:
Model :
Template:
As the comment in his answer suggests this is more extendable.
Actually, you can use
arguments
inside of your template:If you check source code for generated template function, you will see something like this:
What happens here: at first JS tries to find your property in "obj", which is model (more about with statement). This property is not found in "obj" scope, so JS traverses up and up until global scope and finally throws exception.
So, you can specify your scope directly to fix that:
At least it worked for me.
Actually, you can access vars like initial object properties.
If you'll activate debugger into template, you can find variable "obj", that contains all your data.
So instead of
<%= title %>
you should write<%= obj.title %>
Pass the template data inside a wrapper object. Missing property access won't throw an error:
So, instead of:
Try:
A very simple solution: you can ensure that your data collection is normalized, i.e. that all properties are present in each object (with a null value if they are unused). A function like this can help:
(Note:
_.zipObject
and_.fill
are available in recent versions of lodash but not underscore)Use it like this:
Of course, you don't have to transform your data permanently – just invoke the function on the fly as you call your template rendering function: