未定义不是功能问题

时间:2014-04-14 21:50:55

标签: javascript jquery backbone.js underscore.js

我有一个Backbone.js应用程序,它有一个看起来像这样的js文件:

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);
        });

    }

我收到错误:

 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

另外,我的html看起来像:

<div class='item ad' data-type="ad">
  <textarea class='adInput' placeholder='Ad'></textarea>
  <input class='citeInput' type='text'/>
</div>

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

问题出在本声明中:

if (this.$(".adInput").val())
    wd.ad = this.$(".adInput").val();

尝试将其替换为:

if ($(this).find(".adInput").val())
    wd.ad = $(this).find(".adInput").val();

this。$(selector)是View中定义的Backbone方法。你可以看到它here

在每个迭代器调用的匿名函数中,this的上下文发生了变化。它不再是指视图。您可以使用$(this)来获取每个迭代器当前正在处理的元素,并使用find来选择属于它的层次结构的元素。这正是Backbone的视图$方法所做的。

$: function(selector) {
   return this.$el.find(selector);
}

同样纠正其他2个块。

答案 1 :(得分:0)

更改此

 var wd = new Object(); 

到这个

var wd = {ad: '', cite: '', address: ''};

而且(&#34; .addressInput&#34;)无效,因为我无法使用此类在HTML中找到任何DOM元素