Windows 8–Custom WinRT components and WinJS

Posted by Jonas Bush on Geeks with Blogs See other posts from Geeks with Blogs or by Jonas Bush
Published on Sat, 25 Aug 2012 22:24:00 GMT Indexed on 2012/08/27 21:40 UTC
Read the original article Hit count: 373

Filed under:

Wow, I’m still alive!

I installed the RTM of Windows 8 when it became available, and in the last few days have started taking a look at writing a windows 8 app using HTML/JS, which in and of itself is a weird thing. I don’t think that windows developers of 10 years ago would’ve thought something like this would have ever come about.

As I was working on this, I ran across a problem, found the solution, and thought I’d blog about it to try and kick start me back into blogging. I already answered my own question on Stack Overflow, but will explain here.

I needed to create a custom WinRT component to do some stuff that I either wouldn’t be able to or didn’t know how to do with the javascript libraries available to me. I had a javascript class defined like this:

WinJS.Namespace.define("MyApp", {
  MyClass: WinJS.Class.define(function() {
    //constructor function
  },
  { /*instance members*/ },
  { /*static members*/ })
});

This gives me an object I can access in javascript: var foo = new MyApp.MyClass();

I created my WinRT component like this:

namespace MyApp
{
  public sealed class SomeClass
  {
    public int SomeMethod()
    {
      return 42;
    }
  }
}

 

With the thought that from my javascript, I’d be able to do this:

var foo = new MyApp.MyClass();
var bar = new MyApp.SomeClass(); //from WinRT component
foo.SomeProperty = bar.SomeMethod();

 

When I tried this, I got the following error when trying to construct MyApp.MyClass (the object defined in Javascript)

0x800a01bd - Javascript runtime error: Object doesn't support this action.

I puzzled for a bit, then noticed while debugging that my “MyApp” namespace didn’t have anything in it other than the WinRT component. I changed my WinRT component to this:

namespace MyAppUtils
{
  public sealed class SomeClass
  {
    //etc
  }
}
And after this, everything was fine. So, lesson learned: If you’re using Javascript and create a custom WinRT component, make sure that the WinRT component is in a namespace all its own. Not sure why this happens, and if I find out why or if MS says something about this somewhere, I’ll come back and update this.

© Geeks with Blogs or respective owner