MacRuby: общение с Objective C из JavaScript - PullRequest
1 голос
/ 20 декабря 2011

Я создаю простое приложение "hello world", чтобы попытаться понять, как вызвать Objective-C из JavaScript.Мои методы sayHello() и sayGoodBye() работают, но мой метод speak(text) не работает.Что я делаю неправильно?И почему мне нужно указать @com.respondsToSelector, хотя я указал self.isSelectorExcludedFromWebScript?

page.html

<!DOCTYPE html>
<html>
<body>
    <h3>Example of calling MacRuby/Objective-C from a web page</h3>
    <button onclick="Communicator.sayHello()">Hello</button>
    <button onclick="Communicator.sayGoodBye()">Good Bye</button>
    <button onclick="Communicator.speak('passing an argument')">Pass an argument</button>
</body>
</html>

app.rb

framework 'Cocoa'
framework 'WebKit'

application = NSApplication.sharedApplication

class Communicator
  def sayHello
    speak('Hello!')
  end

  def sayGoodBye
    speak('Good Bye!')
  end

  def speak(text)
    puts "Speaking: #{text}"
    speaker = NSSpeechSynthesizer.alloc.initWithVoice('com.apple.speech.synthesis.voice.Agnes')
    speaker.startSpeakingString(text)
  end

  # Make all the Communicator's methods available from JS
  def self.isSelectorExcludedFromWebScript(sel); false end
end

class Browser

  attr_accessor :view, :windowScriptObject

  def initialize(window)
    @view   = WebView.new
    window.contentView = @view
    @view.frameLoadDelegate = self
  end

  def load
    file_url = NSURL.fileURLWithPath('page.html')
    html = NSString.stringWithContentsOfURL(file_url)
    @view.mainFrame.loadHTMLString(html, baseURL:file_url)
  end

  def webView(view, didFinishLoadForFrame:frame)
    @com  = Communicator.new
    #shouldnt need any of these
    @com.respondsToSelector("sayHello")
    @com.respondsToSelector("sayGoodBye")
    @com.respondsToSelector("speak:") # colon at the end of method name because it accepts arguments

    @windowScriptObject = view.windowScriptObject
    @windowScriptObject.setValue(@com, forKey: "Communicator")
  end

end

window = NSWindow.alloc.initWithContentRect([0.0, 0.0, 700.0, 300.0], # x, y, width, height
          styleMask: NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSResizableWindowMask,
          backing:NSBackingStoreBuffered,
          defer:false)

browser = Browser.new(window).load

window.center
window.display
window.makeKeyAndOrderFront(nil)
window.orderFrontRegardless

application.run
...