2013-06-06 98 views
0

我想讓一個頁面加載運行'搜索'功能,但我在self.search(event)中收到錯誤消息。 請幫助那裏,我怎麼能頁面加載調用搜索功能?Jquery TypeError:Object [object global]沒有方法'搜索'

directory.views.SearchPage = Backbone.View.extend({ 

templateLoader: directory.utils.templateLoader, 

initialize: function() { 
    this.template = _.template(this.templateLoader.get('search-page')); 
    this.render(); 
    var keyword = '_firstkey'; 
    $(document).ready(function (event) { 
    self.search(event); //Uncaught TypeError: Object [object global] has no method 'search'## 

    }) 
}, 

render: function(eventName) { 
    $(this.el).html(this.template(this.model.toJSON())); 
    this.listView = new directory.views.EmployeeListView({el: $('.scroll', this.el), model: this.model}); 
    this.listView.render(); 
    return this; 
}, 

events: { 
    "keyup .search-key": "search" 
}, 
search: function(event) { 
    var key = $('.search-key').val(); 
    this.model.findByName(key); 
    return false; 
}, 
}); 

回答

1

您還沒有定義initialize方法裏面self變量,你需要創建像var self = this;

directory.views.SearchPage = Backbone.View.extend({ 

    templateLoader: directory.utils.templateLoader, 

    initialize: function() { 
     this.template = _.template(this.templateLoader.get('search-page')); 
     this.render(); 
     var keyword = '_firstkey'; 
     var self = this; //add self variable here 
     $(document).ready(function (event) { 
      self.search(event); //Uncaught TypeError: Object [object global] has no method 'search'## 

     }) 
    }, 

    render: function(eventName) { 
     $(this.el).html(this.template(this.model.toJSON())); 
     this.listView = new directory.views.EmployeeListView({el: $('.scroll', this.el), model: this.model}); 
     this.listView.render(); 
     return this; 
    }, 

    events: { 
     "keyup .search-key": "search" 
    }, 
    search: function(event) { 
     var key = $('.search-key').val(); 
     this.model.findByName(key); 
     return false; 
    } 
}); 
+0

封閉變量可能會告訴我們有用的,爲什麼錯誤信息是「沒有這樣的方法「而不是ReferenceError或」undefined不是對象「。 –

+0

@ muistooshort這裏'self'似乎指向'window'(全局對象)。在chrome中至少有'self'存在於全球空間 –

+1

https://developer.mozilla.org/en-US/docs/Web/API/window.self(這就是爲什麼正確的偏執狂人們不會使用'self'爲此目的,'_this'和'that'是更好的選擇) –

相關問題