-->

Unable to access NameSpace.app variables with ST2?

2019-05-21 14:52发布

问题:

I'm using the Sencha Command Line 3 tools with a newly generated Sencha Touch 2 application.

Assuming my app.js file looks like this:

Ext.application({
  name: "CA",
  event_code: "test123",
  launch: function() {
   console.log("application launched!");
  }
});

My views and object stores depend on generating a URL based on CA.app.event_code equaling "test123";

During development in the browser, everything works fine, CA.app returns the variables I need.

When I compile my application with sencha app build and try to run the minified version in the browser, I get an error like this:

Error evaluating http://localhost:8888/app.js with message: TypeError: Cannot read property 'event_code' of undefined localhost:11

I'm not entirely sure why this is happening or how I can fix it. I am open to any and all ideas or suggestions, any pointers in the right direction will be greatly appreciated.

回答1:

Ran into the exact same issue. You have no access to the namespaced app within the views... really sucks that they let you in development and not when built. Anyway, I got around it by adding a static helper class and using that all over my app:

In /app/util/Helper.js:

Ext.define('MyApp.util.Helper', {
  singleton: true,
  alternateClassName: 'Helper',
  config: {
    foo: "bar",
    bat: "baz"
  },
  staticFunction: function() {
    // whatever you need to do...
  }
});

Then in your view or controller:

Ext.define('MyApp.view.SomeView', {
  ...
  requires: ['Events.util.Helper'],
  ...
  someViewFunction: function() {
    var someValue = Helper.staticFunction();
    // and you can use Helper.foo or Helper.bat in here
  }
});

For reference, here's some documentation on Sencha Singletons. And one important note: make sure that your Helper singleton is in it's own file! If it's small, you may be inclined to put it at the bottom of your app.js, and things will work at first, and the build process will work, but the code will not. Don't worry, the build process puts all of your JS code in one big, compressed file anyway.