CoffeeScript class extends - TypeError: Object #<Google> has no method 'perform'
class Search
perform: (text) ->
query = encodeURIComponent text
results = ''
request {uri: @uri + query }, (error, response, body) =>
if !error? && response.statusCode == 200
window = jsdom.jsdom(body).createWindow()
jsdom.jQueryify window, './jquery-1.5.min.js', (window, jquery) =>
$ = window.$
jquery(@pattern).each (i, lmn) =>
link = $(lmn).text() + " - " + $(lmn).attr('href')
if requiresHttp? && /^http/.exec $(lmn).attr('href')
results = results + link + "\n"
else
results = results + link + "\n"
@emit 'end', results
sys.inherits(Search, process.EventEmitter)
class Google extends Search
@uri = 'http://www.google.com/search?q='
@pattern = '#ires ol li .r a'
When I execute
google = new Google
google.perform 'blah'
It's returning the error "TypeError: Object #Google has no method 'perform'". Shouldn't the extend provide that method?
UPDATE
Shortly after posting I re-factored the code. Here is the working result:
{EventEmitter} = require "events"
request = require 'request'
jsdom = require 'jsdom'
class Search extends EventEmitter
constructor: ->
@linkPrefix = ''
@requiresHttp = false
@uri = ''
@pattern = ''
perform: (text) ->
query = encodeURIComponent text
results = ''
request {uri: @uri + query }, (error, response, body) =>
if !error? && response.statusCode == 200
window = jsdom.jsdom(body).createWindow()
jsdom.jQueryify window, './jquery-1.5.min.js', (window, jquery) =>
$ = window.$
jquery(@pattern).each (i, lmn) =>
link = $(lmn).text() + " - " + @linkPrefix + $(lmn).attr('href')
if @requiresHttp?
if /^http/.exec $(lmn).attr('href')
results = results + link + "\n"
else
results = results + link + "\n"
@emit 'end', results
class Google extends Search
constructor: ->
@uri = 'http://www.google.com/search?q='
@pattern = '#ires ol li .r a'
@requiresHttp = true
class Youtube extends Search
constructor: ->
@uri = 'http://www.youtube.com/results?search_query='
@pattern = '#search-results h3 a'
@linkPrefix = 'http://www.youtube.com'
exports.Google = Google
exports.Youtube = You开发者_StackOverflow社区tube
CD Sandchez's comment is correct. If you cut out the sys.inherits
line, then perform
runs.
What you should do instead is use CoffeeScript inheritance all the way:
class Search extends process.EventEmitter
精彩评论