TooTallNate / NodObjC

The Node.js ⇆ Objective-C bridge

Home Page:http://tootallnate.github.io/NodObjC

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

bypassing class caching?

nw opened this issue · comments

Example code:

var $ = require('nodobjc');
$.framework('Cocoa');

setInterval(function(){
  var current_app = $.NSWorkspace('sharedWorkspace')('frontmostApplication')('localizedName');
  console.log(current_app);
}, 1000);

This will always return the same result. I saw references to class caching, is this what I'm running into?

If I change the code to:

//check.js
var $ = require('nodobjc');
$.framework('Cocoa');
var current_app = $.NSWorkspace('sharedWorkspace')('frontmostApplication')('localizedName');
console.log(current_app);

run with:

var exec = require('child_process').exec;

setInterval(function(){
exec('node check.js', function(err, result){
  console.log(result)
})  
}, 1000);

This works as expected, but dirty as hell. How can I break the caching on the class?

Thanks!

you can subscribe to change notifications by making a homemade run loop like:

w = $.NSWorkspace('sharedWorkspace')
n = w('notificationCenter')
app = $.NSApplication('sharedApplication')
AppDelegate = $.NSObject.extend('AppDelegate')

AppDelegate.addMethod 'applicationChanged:', 'v@:@', (self, _cmd, notification) ->
  # do something with the current application

AppDelegate.register()
delegate = AppDelegate('alloc')('init')
app('setDelegate', delegate)
n('addObserver', delegate, 'selector', 'applicationChanged:', 'name', $('NSWorkspaceDidActivateApplicationNotification'), 'object', null )

mask = $.NSAnyEventMask.toString()
mode = $('kCFRunLoopDefaultMode')

tock = ->
  ev = undefined
  while ev = app('nextEventMatchingMask', mask, 'untilDate', null, 'inMode', mode, 'dequeue', 1)
    app 'sendEvent', ev
  setTimeout tock, 300 # or whatever

app 'finishLaunching'
tock()

you can also use applescript:

applescript = (content, shouldReturn=true) ->
    script = $.NSAppleScript('alloc')('initWithSource', $(content))
    results = script('executeAndReturnError', null)
    if shouldReturn
      results('stringValue')?.toString()
    else
      null

currentApp = applescript """
  tell application "System Events" to get the name of first process where frontmost is true
"""

@unboundmusic thank you!

The EventLoop example make much more sense now.