Reputation: 1173
I have a Backbone.js application that has a js file that looks like:
var ProductView = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'render','createProduct');
this.render();
},
events: {
"click #createProduct": "createProduct"
},
render: function() {
var source = $('#product-template').html();
var template = Handlebars.compile(source);
var html = template(this.model.toJSON());
this.$el.html(html);
},
createProduct: function(){
var product_title = this.$(".title").val();
var product_description = this.$(".description").val();
var data = [];
$(".product").each( function(){
var type = $( this ).data("type");
var wd = new Object();
if (this.$(".adInput").val()) { wd.ad = this.$(".adInput").val(); }
if (this.$(".citeInput").val()) { wd.cite = this.$(".citeInput").val(); }
if (this.$(".addressInput").val()) { wd.address = this.$(".addressInput").val(); }
alert(wd);
});
}
I'm getting the error:
Uncaught TypeError: undefined is not a function main.js?body=1:61
(anonymous function) main.js?body=1:61
jQuery.extend.each jquery.js?body=1:385
jQuery.fn.jQuery.each jquery.js?body=1:138
Backbone.View.extend.createProduct main.js?body=1:56
jQuery.event.dispatch jquery.js?body=1:4625
elemData.handle
Also, my html looks like:
<div class='item ad' data-type="ad">
<textarea class='adInput' placeholder='Ad'></textarea>
<input class='citeInput' type='text'/>
</div>
Thanks for all help!
Upvotes: 0
Views: 245
Reputation: 17615
Issue is in this statement :
if (this.$(".adInput").val())
wd.ad = this.$(".adInput").val();
Try replacing it with :
if ($(this).find(".adInput").val())
wd.ad = $(this).find(".adInput").val();
this.$(selector) is a Backbone method defined in a View. You can see it here.
In the anonymous function invoked by each iterator, the context of this
gets changed. It no more refers to the View. You can use $(this) to get the element being currently processed by the each iterator and use find on it to select elements which belong to it's hierarchy. This is exactly what Backbone's view $ method does.
$: function(selector) {
return this.$el.find(selector);
}
Similarly correct the other 2 if blocks.
Upvotes: 1
Reputation: 4824
Change this
var wd = new Object();
to this
var wd = {ad: '', cite: '', address: ''};
And (".addressInput") is invalid because i cant find any DOM element in your HTML with this class
Upvotes: 0