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'
执行时
google = new Google
google.perform 'blah'
它返回错误“TypeError:Object #Google没有方法'执行'”。扩展不应该提供这种方法吗?
更新
发布后不久我重新考虑了代码。以下是工作结果:
{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 = Youtube
答案 0 :(得分:3)
CD Sandchez的评论是正确的。如果您删除sys.inherits
行,则perform
会运行。
你应该做的是使用CoffeeScript继承:
class Search extends process.EventEmitter